aosdict
aosdict

Reputation: 150

Content script event listener not working in all tabs? (Firefox add-on SDK)

In my Firefox SDK add-on, I have a simple content script that adds a keydown event listener to its page and logs the event:

//content-script.js
console.log("Running");
window.addEventListener("keydown", function(event) {
  console.log("Key down event");
});
window.focus();

And I have written a function to set up this behavior in main.js:

//main.js
function setupTab(tab) {
  console.log("setup");
  tab.attach({
    contentScriptFile: "./content-script.js"
  });
}

tabs.on("open", function(tab) {
  setupTab(tab);
});
setupTab(tabs.activeTab);

My ultimate goal is to run the content script on all tabs that are open when the add-on starts up, as well as any tabs that open afterward. For the moment I am just running this on the active tab and all subsequently opened ones.

When I run the add-on, the console logs "setup" and "Running" and also logs any key presses I make in the initial window, which is the expected behavior. However, when I open new tabs, the first new tab opened will log both "setup" and "Running" but they will NOT log any keypresses. Every new tab after that will log "setup", "Running", and keypresses.

I have noticed that the Add-on SDK version of Firefox runs like a fresh installation each time, and the first new tab opened (and only this tab) pops up a "What is this page?" message. This might be interfering somehow, but if so I don't know how to circumvent it.

Upvotes: 0

Views: 430

Answers (1)

Christos Papoulas
Christos Papoulas

Reputation: 2568

I'm suspecting that the behaviour you want is at every active tab. So the code may be like this:

//main.js
var tabs = require("sdk/tabs");    
tabs.on('ready', function (tab) {
    tabs.activeTab.attach({
      contentScriptFile: "./content-script.js"
    })
});

Upvotes: 1

Related Questions