Search code examples
firefoxsdkfirefox-addonfirefox-addon-sdk

Firefox extension addon tab using background script


I have a firefox extension that opens up a tab with a html file that is located in my data folder. The main.js does this:

 function handleClick(state) {
   tabs.open("login.html");
  }

In main.js I require() a bunch of scripts to run as background scripts. This html file acts as the "login" for the extension. How can this html page have access to the background scripts?


Solution

  • It can't. You'll need to attach a content script to your login page and to send variables to it the standard way using port.

    Also, does your code work? Don't you need to require(sdk/self).data to get access to login.html?

    Here's an example of what you can do.

    main.js

    const { data } = require('sdk/self');
    
    function handleClick(state) {
      tabs.open({
        url: data.url('login.html'),
        onOpen: function(tab) {
          var worker = tab.attach({
            contentScriptFile: data.url('login.js')
          });
          worker.port.emit('foo', foo);
          worker.port.on('bar', handleBar);
        }
      });
    }
    
    function handleBar(bar) {
      // do something with bar;
    }
    

    login.js

    self.port.on('foo', function(foo) {
      // do something with foo
    });
    
    self.port.emit('bar', bar);