Search code examples
firefoxtabsfirefox-addonclipboardfirefox-addon-sdk

How to pass a value between browser tabs?


I am trying to pass a value from one tab to another.

I tried sessionStorage and clipboard, but no luck so far. Here is the demo, and the code as well:

https://builder.addons.mozilla.org/package/154290/latest/

What it tries to do is get the selected text, and pass it to the opened tab:

// Create a new context menu item.
var menuItem = contextMenu.Item({
    label: "Check with Proofread Bot",
    context: contextMenu.SelectionContext(),
    contentScript: 'self.on("click", function () {' +
                '  var text = window.getSelection().toString();' +
                '  sessionStorage.setItem("proofread_bot_chrome", text);' +
                '  self.postMessage(text);' +
                        '});',
    onMessage: function(text) {
        clipboard.set(text);
        //sessionStorage.setItem("proofread_bot_chrome", text);
        tabs.open({
          url: "http://proofreadbot.com",
          onOpen: function onOpen(tab) {
            // do stuff like listen for content
            // loading.
            alert(clipboard.get());
            alert(selection.text);
            sessionStorage.setItem("proofread_bot_chrome", clipboard.get());
          }
        });
    }
});

Solution

  • sessionStorage and localStorage are always bound to a domain. Content scripts run with the privileges of the web page meaning that they access the session storage for that web page - not very useful to pass data around. And they simply don't have clipboard access.

    This means that you can't get around "traditional" messaging. When you open the tab you should attach a content script, wait for it to be ready (the content script can send a message to indicate that) and send it the text. Something like this:

    onOpen: function(tab) {
      var worker = tab.attach({
        contentScript: "self.on('message', function(text) {alert(text);});" +
                       "self.postMessage(null);",
        onMessage: function() {
          worker.postMessage(text);
        }
      });
    }
    

    For reference: Communicating using postMessage()