Search code examples
tabsfirefox-addon-sdk

Firefox Addon SDK - how to make page in new tabs run only once


I am new to Firefox Addon SDK, high level API.

What I wanted to do it, if a user click the icon on the toolbar, a new tab is opened, and run the script defined in contentscriptfile.

I use the script below:

var self = require("sdk/self");
var tabs = require("sdk/tabs");
var buttons = require('sdk/ui/button/action');

var button = buttons.ActionButton({
  id: "mm-link",
  label: "Visit mm",
  icon: {
    "32": "./icon-32.png",
    "64": "./icon-64.png"
  },
  onClick: handleClick
});

function handleClick(state) {
  tabs.open("about:blank");
  tabs.on('ready', function (tab) {
    tab.attach({
      contentScriptFile: self.data.url("home.js"),
      contentScriptOptions: {"aaa" : "1111", "bob" : "222"}
    });
});
}

But it doesn't work as expected, and has the following problems:

  1. The script runs repeatedly. (I wanted it run only once on each new tab)
  2. Even if I click the "+" icon to create a new tab, the script will run. (I wanted it only run when clicking the icon I created on the toolbar)

I have also tried to change 'ready' to 'activiate', the repeated running problem is gone, but every time I create the tab, the script will run.

Many thanks to any help.


Solution

  • The issue is that you're listening to the ready event of any and all tabs, rather than the one you just opened. One option is to do something like this:

    function handleClick(state) {
        tabs.open({
            url: "about:blank",
            onOpen: function onOpen(tab) {
                tab.attach({
                    contentScriptFile: self.data.url("home.js"),
                    contentScriptOptions: {"aaa" : "1111", "bob" : "222"}
                });
            }
        });
    }
    

    And attach the script using the onOpen handler. For more info the docs are here: https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs#open%28options%29