summaryrefslogtreecommitdiffstats
path: root/browser/extensions/pocket/content/main.js
blob: 3c1c5785ea3973685969c2b9f6501a1554958b0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
/*
 * LICENSE
 *
 * POCKET MARKS
 *
 * Notwithstanding the permitted uses of the Software (as defined below) pursuant to the license set forth below, "Pocket," "Read It Later" and the Pocket icon and logos (collectively, the “Pocket Marks”) are registered and common law trademarks of Read It Later, Inc. This means that, while you have considerable freedom to redistribute and modify the Software, there are tight restrictions on your ability to use the Pocket Marks. This license does not grant you any rights to use the Pocket Marks except as they are embodied in the Software.
 *
 * ---
 *
 * SOFTWARE
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Pocket UI module
 *
 * Handles interactions with Pocket buttons, panels and menus.
 *
 */

// TODO : Get the toolbar icons from Firefox's build (Nikki needs to give us a red saved icon)
// TODO : [needs clarificaiton from Fx] Firefox's plan was to hide Pocket from context menus until the user logs in. Now that it's an extension I'm wondering if we still need to do this.
// TODO : [needs clarificaiton from Fx] Reader mode (might be a something they need to do since it's in html, need to investigate their code)
// TODO : [needs clarificaiton from Fx] Move prefs within pktApi.s to sqlite or a local file so it's not editable (and is safer)
// TODO : [nice to have] - Immediately save, buffer the actions in a local queue and send (so it works offline, works like our native extensions)

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
  "resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ReaderMode",
  "resource://gre/modules/ReaderMode.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "pktApi",
  "chrome://pocket/content/pktApi.jsm");

var pktUI = (function() {

    // -- Initialization (on startup and new windows) -- //
    var _currentPanelDidShow;
    var _currentPanelDidHide;

    // Init panel id at 0. The first actual panel id will have the number 1 so
    // in case at some point any panel has the id 0 we know there is something
    // wrong
    var _panelId = 0;

    var overflowMenuWidth = 230;
    var overflowMenuHeight = 475;
    var savePanelWidth = 350;
    var savePanelHeights = {collapsed: 153, expanded: 272};

    // -- Event Handling -- //

    /**
     * Event handler when Pocket toolbar button is pressed
     */

    function pocketPanelDidShow(event) {
        if (_currentPanelDidShow) {
            _currentPanelDidShow(event);
        }

    }

    function pocketPanelDidHide(event) {
        if (_currentPanelDidHide) {
            _currentPanelDidHide(event);
        }

        // clear the panel
        getPanelFrame().setAttribute('src', 'about:blank');
    }


    // -- Communication to API -- //

    /**
     * Either save or attempt to log the user in
     */
    function tryToSaveCurrentPage() {
        tryToSaveUrl(getCurrentUrl(), getCurrentTitle());
    }

    function tryToSaveUrl(url, title) {

        // If the user is logged in, go ahead and save the current page
        if (pktApi.isUserLoggedIn()) {
            saveAndShowConfirmation(url, title);
            return;
        }

        // If the user is not logged in, show the logged-out state to prompt them to authenticate
        showSignUp();
    }


    // -- Panel UI -- //

    /**
     * Show the sign-up panel
     */
    function showSignUp() {
        // AB test: Direct logged-out users to tab vs panel
        if (pktApi.getSignupPanelTabTestVariant() == 'v2')
        {
            let site = Services.prefs.getCharPref("extensions.pocket.site");
            openTabWithUrl('https://' + site + '/firefox_learnmore?s=ffi&t=autoredirect&tv=page_learnmore&src=ff_ext', true);

            // force the panel closed before it opens
            getPanel().hidePopup();

            return;
        }

        // Control: Show panel as normal
        getFirefoxAccountSignedInUser(function(userdata)
        {
            var fxasignedin = (typeof userdata == 'object' && userdata !== null) ? '1' : '0';
            var startheight = 490;
            var inOverflowMenu = isInOverflowMenu();
            var controlvariant = pktApi.getSignupPanelTabTestVariant() == 'control';

            if (inOverflowMenu)
            {
                startheight = overflowMenuHeight;
            }
            else
            {
                startheight = 460;
                if (fxasignedin == '1')
                {
                    startheight = 406;
                }
            }
            if (!controlvariant) {
                startheight = 427;
            }
            var variant;
            if (inOverflowMenu)
            {
                variant = 'overflow';
            }
            else
            {
                variant = 'storyboard_lm';
            }

            showPanel("about:pocket-signup?pockethost="
                + Services.prefs.getCharPref("extensions.pocket.site")
                + "&fxasignedin="
                + fxasignedin
                + "&variant="
                + variant
                + '&controlvariant='
                + controlvariant
                + '&inoverflowmenu='
                + inOverflowMenu
                + "&locale="
                + getUILocale(), {
                    onShow: function() {
                    },
                    onHide: panelDidHide,
                    width: inOverflowMenu ? overflowMenuWidth : 300,
                    height: startheight
            });
        });
    }

    /**
     * Show the logged-out state / sign-up panel
     */
    function saveAndShowConfirmation(url, title) {

        // Validate input parameter
        if (typeof url !== 'undefined' && url.startsWith("about:reader?url=")) {
            url = ReaderMode.getOriginalUrl(url);
        }

        var isValidURL = (typeof url !== 'undefined' && (url.startsWith("http") || url.startsWith('https')));

        var inOverflowMenu = isInOverflowMenu();
        var startheight = pktApi.isPremiumUser() && isValidURL ? savePanelHeights.expanded : savePanelHeights.collapsed;
        if (inOverflowMenu) {
            startheight = overflowMenuHeight;
        }

        var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? '1' : '0') + '&inoverflowmenu='+inOverflowMenu + "&locale=" + getUILocale(), {
            onShow: function() {
                var saveLinkMessageId = 'saveLink';

                // Send error message for invalid url
                if (!isValidURL) {
                    // TODO: Pass key for localized error in error object
                    let error = {
                        message: 'Only links can be saved',
                        localizedKey: "onlylinkssaved"
                    };
                    pktUIMessaging.sendErrorMessageToPanel(panelId, saveLinkMessageId, error);
                    return;
                }

                // Check online state
                if (!navigator.onLine) {
                    // TODO: Pass key for localized error in error object
                    let error = {
                        message: 'You must be connected to the Internet in order to save to Pocket. Please connect to the Internet and try again.'
                    };
                    pktUIMessaging.sendErrorMessageToPanel(panelId, saveLinkMessageId, error);
                    return;
                }

                // Add url
                var options = {
                    success: function(data, request) {
                        var item = data.item;
                        var successResponse = {
                            status: "success",
                            item: item
                        };
                        pktUIMessaging.sendMessageToPanel(panelId, saveLinkMessageId, successResponse);
                    },
                    error: function(error, request) {
                        // If user is not authorized show singup page
                        if (request.status === 401) {
                            showSignUp();
                            return;
                        }

                        // If there is no error message in the error use a
                        // complete catch-all
                        var errorMessage = error.message || "There was an error when trying to save to Pocket.";
                        var panelError = { message: errorMessage}

                        // Send error message to panel
                        pktUIMessaging.sendErrorMessageToPanel(panelId, saveLinkMessageId, panelError);
                    }
                }

                // Add title if given
                if (typeof title !== "undefined") {
                    options.title = title;
                }

                // Send the link
                pktApi.addLink(url, options);
            },
            onHide: panelDidHide,
            width: inOverflowMenu ? overflowMenuWidth : savePanelWidth,
            height: startheight
        });
    }

    /**
     * Open a generic panel
     */
    function showPanel(url, options) {

        // Add new panel id
        _panelId += 1;
        url += ("&panelId=" + _panelId);

        // We don't have to hide and show the panel again if it's already shown
        // as if the user tries to click again on the toolbar button the overlay
        // will close instead of the button will be clicked
        var iframe = getPanelFrame();

        // Register event handlers
        registerEventMessages();

        // Load the iframe
        iframe.setAttribute('src', url);

        // Uncomment to leave panel open -- for debugging
        // panel.setAttribute('noautohide', true);
        // panel.setAttribute('consumeoutsideclicks', false);
        //

        // For some reason setting onpopupshown and onpopuphidden on the panel directly didn't work, so
        // do it this hacky way for now
        _currentPanelDidShow = options.onShow;
        _currentPanelDidHide = options.onHide;

        resizePanel({
            width: options.width,
            height: options.height
        });
        return _panelId;
    }

    /**
     * Resize the panel
     * options = {
     *  width: ,
     *  height: ,
     *  animate [default false]
     * }
     */
    function resizePanel(options) {
        var iframe = getPanelFrame();
        var subview = getSubview();

        if (subview) {
          // Use the subview's size
          iframe.style.width = "100%";
          iframe.style.height = subview.parentNode.clientHeight + "px";
        } else {
          // Set an explicit size, panel will adapt.
          iframe.style.width  = options.width  + "px";
          iframe.style.height = options.height + "px";
        }
    }

    /**
     * Called when the signup and saved panel was hidden
     */
    function panelDidHide() {
        // clear the onShow and onHide values
        _currentPanelDidShow = null;
        _currentPanelDidHide = null;
    }

    /**
     * Register all of the messages needed for the panels
     */
    function registerEventMessages() {
        var iframe = getPanelFrame();

        // Only register the messages once
        var didInitAttributeKey = 'did_init';
        var didInitMessageListener = iframe.getAttribute(didInitAttributeKey);
        if (typeof didInitMessageListener !== "undefined" && didInitMessageListener == 1) {
            return;
        }
        iframe.setAttribute(didInitAttributeKey, 1);

        // When the panel is displayed it generated an event called
        // "show": we will listen for that event and when it happens,
        // send our own "show" event to the panel's script, so the
        // script can prepare the panel for display.
        var _showMessageId = "show";
        pktUIMessaging.addMessageListener(iframe, _showMessageId, function(panelId, data) {
            // Let panel know that it is ready
            pktUIMessaging.sendMessageToPanel(panelId, _showMessageId);
        });

        // Open a new tab with a given url and activate if
        var _openTabWithUrlMessageId = "openTabWithUrl";
        pktUIMessaging.addMessageListener(iframe, _openTabWithUrlMessageId, function(panelId, data, contentPrincipal) {
            try {
              urlSecurityCheck(data.url, contentPrincipal, Services.scriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
            } catch (ex) {
              return;
            }

            // Check if the tab should become active after opening
            var activate = true;
            if (typeof data.activate !== "undefined") {
                activate = data.activate;
            }

            var url = data.url;
            openTabWithUrl(url, activate);
            pktUIMessaging.sendResponseMessageToPanel(panelId, _openTabWithUrlMessageId, url);
        });

        // Close the panel
        var _closeMessageId = "close";
        pktUIMessaging.addMessageListener(iframe, _closeMessageId, function(panelId, data) {
            getPanel().hidePopup();
        });

        // Send the current url to the panel
        var _getCurrentURLMessageId = "getCurrentURL";
        pktUIMessaging.addMessageListener(iframe, _getCurrentURLMessageId, function(panelId, data) {
            pktUIMessaging.sendResponseMessageToPanel(panelId, _getCurrentURLMessageId, getCurrentUrl());
        });

        var _resizePanelMessageId = "resizePanel";
        pktUIMessaging.addMessageListener(iframe, _resizePanelMessageId, function(panelId, data) {
            resizePanel(data);
        });

        // Callback post initialization to tell background script that panel is "ready" for communication.
        pktUIMessaging.addMessageListener(iframe, "listenerReady", function(panelId, data) {

        });

        pktUIMessaging.addMessageListener(iframe, "collapseSavePanel", function(panelId, data) {
            if (!pktApi.isPremiumUser() && !isInOverflowMenu())
                resizePanel({width:savePanelWidth, height:savePanelHeights.collapsed});
        });

        pktUIMessaging.addMessageListener(iframe, "expandSavePanel", function(panelId, data) {
            if (!isInOverflowMenu())
                resizePanel({width:savePanelWidth, height:savePanelHeights.expanded});
        });

        // Ask for recently accessed/used tags for auto complete
        var _getTagsMessageId = "getTags";
        pktUIMessaging.addMessageListener(iframe, _getTagsMessageId, function(panelId, data) {
            pktApi.getTags(function(tags, usedTags) {
                pktUIMessaging.sendResponseMessageToPanel(panelId, _getTagsMessageId, {
                    tags: tags,
                    usedTags: usedTags
                });
            });
        });

        // Ask for suggested tags based on passed url
        var _getSuggestedTagsMessageId = "getSuggestedTags";
        pktUIMessaging.addMessageListener(iframe, _getSuggestedTagsMessageId, function(panelId, data) {
            pktApi.getSuggestedTagsForURL(data.url, {
                success: function(data, response) {
                    var suggestedTags = data.suggested_tags;
                    var successResponse = {
                        status: "success",
                        value: {
                            suggestedTags: suggestedTags
                        }
                    }
                    pktUIMessaging.sendResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, successResponse);
                },
                error: function(error, response) {
                    pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, error);
                }
            })
        });

        // Pass url and array list of tags, add to existing save item accordingly
        var _addTagsMessageId = "addTags";
        pktUIMessaging.addMessageListener(iframe, _addTagsMessageId, function(panelId, data) {
            pktApi.addTagsToURL(data.url, data.tags, {
                success: function(data, response) {
                    var successResponse = {status: "success"};
                    pktUIMessaging.sendResponseMessageToPanel(panelId, _addTagsMessageId, successResponse);
                },
                error: function(error, response) {
                    pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _addTagsMessageId, error);
                }
            });
        });

        // Based on clicking "remove page" CTA, and passed unique item id, remove the item
        var _deleteItemMessageId = "deleteItem";
        pktUIMessaging.addMessageListener(iframe, _deleteItemMessageId, function(panelId, data) {
            pktApi.deleteItem(data.itemId, {
                success: function(data, response) {
                    var successResponse = {status: "success"};
                    pktUIMessaging.sendResponseMessageToPanel(panelId, _deleteItemMessageId, successResponse);
                },
                error: function(error, response) {
                    pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _deleteItemMessageId, error);
                }
            })
        });

        var _initL10NMessageId = "initL10N";
        pktUIMessaging.addMessageListener(iframe, _initL10NMessageId, function(panelId, data) {
            var strings = {};
            var bundle = Services.strings.createBundle("chrome://pocket/locale/pocket.properties");
            var e = bundle.getSimpleEnumeration();
            while (e.hasMoreElements()) {
                var str = e.getNext().QueryInterface(Components.interfaces.nsIPropertyElement);
                if (str.key in data) {
                    strings[str.key] = bundle.formatStringFromName(str.key, data[str.key], data[str.key].length);
                } else {
                    strings[str.key] = str.value;
                }
            }
            pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings: strings });
        });

    }

    // -- Browser Navigation -- //

    /**
     * Open a new tab with a given url and notify the iframe panel that it was opened
     */

    function openTabWithUrl(url) {
        let recentWindow = Services.wm.getMostRecentWindow("navigator:browser");
        if (!recentWindow) {
          Cu.reportError("Pocket: No open browser windows to openTabWithUrl");
          return;
        }

        // If the user is in permanent private browsing than this is not an issue,
        // since the current window will always share the same cookie jar as the other
        // windows.
        if (!PrivateBrowsingUtils.isWindowPrivate(recentWindow) ||
            PrivateBrowsingUtils.permanentPrivateBrowsing) {
          recentWindow.openUILinkIn(url, "tab");
          return;
        }

        let windows = Services.wm.getEnumerator("navigator:browser");
        while (windows.hasMoreElements()) {
          let win = windows.getNext();
          if (!PrivateBrowsingUtils.isWindowPrivate(win)) {
            win.openUILinkIn(url, "tab");
            return;
          }
        }

        // If there were no non-private windows opened already.
        recentWindow.openUILinkIn(url, "window");
    }


    // -- Helper Functions -- //

    function getCurrentUrl() {
        return getBrowser().currentURI.spec;
    }

    function getCurrentTitle() {
        return getBrowser().contentTitle;
    }

    function getPanel() {
        var frame = getPanelFrame();
        var panel = frame;
        while (panel && panel.localName != "panel") {
            panel = panel.parentNode;
        }
        return panel;
    }

    function getPanelFrame() {
        var frame = document.getElementById('pocket-panel-iframe');
        if (!frame) {
            var frameParent = document.getElementById("PanelUI-pocketView").firstChild;
            frame = document.createElement("iframe");
            frame.id = 'pocket-panel-iframe';
            frame.setAttribute("type", "content");
            frameParent.appendChild(frame);
        }
        return frame;
    }

    function getSubview() {
        var view = document.getElementById("PanelUI-pocketView");
        if (view && view.getAttribute("current") == "true")
            return view;
        return null;
    }

    function isInOverflowMenu() {
        var subview = getSubview();
        return !!subview;
    }

    function getFirefoxAccountSignedInUser(callback) {
        fxAccounts.getSignedInUser().then(userData => {
            callback(userData);
        }).then(null, error => {
            callback();
        });
    }

    function getUILocale() {
        var locale = Cc["@mozilla.org/chrome/chrome-registry;1"].
             getService(Ci.nsIXULChromeRegistry).
             getSelectedLocale("browser");
        return locale;
    }

    /**
     * Public functions
     */
    return {
        getPanelFrame: getPanelFrame,

        openTabWithUrl: openTabWithUrl,

        pocketPanelDidShow: pocketPanelDidShow,
        pocketPanelDidHide: pocketPanelDidHide,

        tryToSaveUrl: tryToSaveUrl,
        tryToSaveCurrentPage: tryToSaveCurrentPage
    };
}());

// -- Communication to Background -- //
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages
var pktUIMessaging = (function() {

    /**
     * Prefix message id for message listening
     */
    function prefixedMessageId(messageId) {
        return 'PKT_' + messageId;
    }

    /**
     * Register a listener and callback for a specific messageId
     */
    function addMessageListener(iframe, messageId, callback) {
        iframe.addEventListener(prefixedMessageId(messageId), function(e) {
            var nodePrincipal = e.target.nodePrincipal;
            // ignore to ensure we do not pick up other events in the browser
            if (!nodePrincipal || !nodePrincipal.URI || !nodePrincipal.URI.spec.startsWith("about:pocket")) {
                return;
            }

            // Pass in information to callback
            var payload = JSON.parse(e.target.getAttribute("payload"))[0];
            var panelId = payload.panelId;
            var data = payload.data;
            callback(panelId, data, nodePrincipal);

            // Cleanup the element
            e.target.parentNode.removeChild(e.target);

        }, false, true);
    }

    /**
     * Send a message to the panel's iframe
     */
    function sendMessageToPanel(panelId, messageId, payload) {

        if (!isPanelIdValid(panelId)) { return; }

        var panelFrame = pktUI.getPanelFrame();
        if (!isPocketPanelFrameValid(panelFrame)) { return; }

        var doc = panelFrame.contentWindow.document;
        var documentElement = doc.documentElement;

        // Send message to panel
        var panelMessageId = prefixedMessageId(panelId + '_' + messageId);

        var AnswerEvt = doc.createElement("PKTMessage");
        AnswerEvt.setAttribute("payload", JSON.stringify([payload]));
        documentElement.appendChild(AnswerEvt);

        var event = doc.createEvent("HTMLEvents");
        event.initEvent(panelMessageId, true, false);
        AnswerEvt.dispatchEvent(event);
    }

    function sendResponseMessageToPanel(panelId, messageId, payload) {
        var responseMessageId = messageId + "Response";
        sendMessageToPanel(panelId, responseMessageId, payload);
    }

    /**
     * Helper function to package an error object and send it to the panel
     * iframe as a message response
     */
    function sendErrorMessageToPanel(panelId, messageId, error) {
        var errorResponse = {status: "error", error: error};
        sendMessageToPanel(panelId, messageId, errorResponse);
    }

    function sendErrorResponseMessageToPanel(panelId, messageId, error) {
        var errorResponse = {status: "error", error: error};
        sendResponseMessageToPanel(panelId, messageId, errorResponse);
    }

    /**
     * Validation
     */

    function isPanelIdValid(panelId) {
        // First check if panelId has a valid value > 0. We set the panelId to
        // 0 to start. But if for some reason the message is attempted to be
        // sent before the panel has a panelId, then it's going to send out
        // a message with panelId 0, which is never going to be heard. If this
        // happens, it means some race condition occurred where the panel was
        // trying to communicate before it should.
        if (panelId === 0) {
            console.warn("Tried to send message to panel with id 0.")
            return false;
        }

        return true
    }

    function isPocketPanelFrameValid(panelFrame) {
        // Check if panel is available if not throw a warning and bailout.
        // We likely try to send to a panel that is not visible anymore
        if (typeof panelFrame === "undefined") {
            console.warn("Pocket panel frame is undefined");
            return false;
        }

        var contentWindow = panelFrame.contentWindow;
        if (typeof contentWindow == "undefined") {
            console.warn("Pocket panel frame content window is undefined");
            return false;
        }

        var doc = contentWindow.document;
        if (typeof doc === "undefined") {
            console.warn("Pocket panel frame content window document is undefined");
            return false;
        }

        var documentElement = doc.documentElement;
        if (typeof documentElement === "undefined") {
            console.warn("Pocket panel frame content window document document element is undefined");
            return false;
        }

        return true;
    }

    /**
     * Public
     */
    return {
        addMessageListener: addMessageListener,
        sendMessageToPanel: sendMessageToPanel,
        sendResponseMessageToPanel: sendResponseMessageToPanel,
        sendErrorMessageToPanel: sendErrorMessageToPanel,
        sendErrorResponseMessageToPanel: sendErrorResponseMessageToPanel
    }
}());