Search code examples
javascriptfirefox-addonfirefox-addon-sdkmessage-passing

Assign click event to addon icon on navigation bar


We have created a chrome extension for our app. Where we call a METHOD from a "js file" on CLICK event of the "extension icon" placed on the navigation bar. For this we use message passing between the app.js (file containing the METHOD to be called on icon click) and background.html (using a js file included in this html). The script used to pass message is:(from background.html)

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.sendMessage(tab.id, "showPopup");
});

and to listen the message :(in app.js)

chrome.extension.onMessage.addListener(function(request) {
   if (request === "showPopup") {
      showPopup();
   }
});

The click event works as expected. But now we want to do same thing in mozilla extension. and we can't pass message to app.js on the click of the icon,so that it can execute the containing methods.

We have also added the app.js using pageMod, something like this

exports.main = function(options, callbacks) {
  pageMod.PageMod({
    include: ["*"],
    contentScriptWhen: 'start',
    contentScriptFile: [data.url('jquery-1.7.1.min.js'),data.url('app.js')]      
  });
  createAndAddNavBarButton();   
};

function createAndAddNavBarButton() {
   var navBar = document.getElementById('nav-bar');//assume document has been defined
   if (!navBar){return;};       
   var nbBtn = document.createElement('navbaricon');    
       nbBtn.setAttribute('id', 'navButton');
       nbBtn.setAttribute('image', data.url('icon_16.png'));        
       nbBtn.onclick = function(){
           showPopup();                    
           return true;
       }    
   navBar.appendChild(btn);
}

But the click event does nothing and showPopup() is undefined. When a new page loads event associated with it in the app.js executes without any error but the click event doesn't work.

Is there a method from where we can assign click event directly to this icon, as we have done in the case of chrome extension.


Solution

  • Was able to send message to the app.js script by message passing. All we have to do is, add the app.js file within the scope of message passing, so that it can communicate with the javascript.

    nbBtn.addEventListener('click', function() {
       var workers = tabs.activeTab.attach({                    
           contentScriptFile: [ data.url("jquery-1.7.1.min.js"), data.url("app.js")]
       });
       workers.postMessage("doABC");
    }, false) 
    
     navBar.appendChild(nbBtn);
    

    Now in app.js we can receive this message and show the popup