segunda-feira, 26 de agosto de 2013

Sending messages from the Document DOM to add script on firefox addon

I'm porting a chrome extension into a firefox one, but there are some differences on how the messages and scripts work on both browsers.

One of the most annoying difference is that the addon's API are not available for the page DOM on firefox like they are on chrome. There is now way to use messages like on firefox like on chrome extensions one-time requests. To send messages from the DOM to the add-on you need to actually emit an event from the DOM script, listen to this event on the content_script and then send the message to the add-on script.

Add on the onclick of an element the CustomEvent:

onclick="var event = new CustomEvent(\'tpemit\', {\'detail\': '+partner_id+'});"

And listen to the event:

document.addEventListener('tpemit', function (e) {
  console.log("event emit"+e.detail);
  [...]
  return true;
});



Content_script.js:
// The event listener:

document.addEventListener('tpemit', function (e) {
  console.log("event emit"+e.detail);
  self.port.emit('tpemit', e.detail);
  return true;
});

// Adding an element to the dom:

popup = document.createElement('div');
popup.innerHTML ='<button type="button" id="_btn_close" onclick="var event = new CustomEvent(\'tpemit\', {\'detail\': '+partner_id+'});">close</button>';
document.body.appendChild(popup);


Thanks to bwinton for helping with this issue. Code snippets used as inspiration:
https://github.com/bwinton/newtab/blob/master/addon/data/content.js#L14
https://github.com/bwinton/newtab/blob/master/website/main/scripts/App.js#L18