Tuesday, 17 June 2014

Firefox addon - Pass data between addon script and content script

In this blog, I am going to describe how to pass data between addon script and content script of Firefox addon.

Those familiar with Firefox addon would know about addon script and content script files.

Firefox sdk provides various apis to interact with local system attributes such as registry keys, clipboard content, context menu etc. And these apis could be accessed from a script called addon script (main.js under lib folder of addon).

But from this addon script, we cannot access any of the document object that contains the html details of web page that we load in browsers. To access document object, we need to use separate script called content script that could be accessed from data folder. These restrictions are introduced to ensure the security of user information.

This article from developer website provides detailed information about the features of addon script and content script.

As far as communication between addon script and content script, they have a feature called 'port', which enables the user to send and receive data between the scripts.

In this blog, I am explaining about how to send and receive the data using PageMod module. We can also send and receive information from other modules such as tabs and panel.

Have the below code in main.js file:

  include: "*",
  contentScriptFile: data.url("textscript.js"),
  contentScriptWhen: "ready",
  onAttach: startListening

function startListening(worker) {
    worker.port.emit('check','test emit');

Here, we are attaching 'startListening' function with PageMod object and it emits a message 'test emit' with the user defined event 'check'.

And in contentscript, below code will capture the data emitted by addon script:

self.port.on('check', function(message) {

Similarly, you can emit the message from content script and can receive it in addon script. You can find those details here: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts

No comments:

Post a Comment