简体   繁体   中英

How to call a content script function from main.js in firefox addon

I am new to Firefox addon development.

I need a way to call a contentscript function from main.js in firefox addon.

I have injected contentscript xyz.js on every opening webpage.

I want to call function abc() present in my contentscript xyz.js from my main.js on click of a button which i have place in navigation toolbar.

Below is my code.

Main.js

..
function addToolbarButton() {
    var document = mediator.getMostRecentWindow('navigator:browser').document;        
    var navBar = document.getElementById('nav-bar');
    if (!navBar) {
        return;
    }
    var btn = document.createElement('toolbarbutton');  
    btn.setAttribute('id', 'mybutton-id');
    btn.setAttribute('type', 'button');
    btn.setAttribute('class', 'toolbarbutton-1');
    btn.setAttribute('image', data.url('icon_16.png'));
    btn.setAttribute('orient', 'vertical');
        btn.setAttribute('label', 'Test');
        btn.addEventListener('click', function() {
            tabs.activeTab.attach({
            //

                abc()     //here i want to call the function present in my contentscript 

            //
        });
        }, false)
    navBar.appendChild(btn);
}

..

xyz.js

..

function abc(){
//here is my code logic
}

..

I came to know that message passing is way to do so but unable to implement in firefox.

Please help me i have got stuckd.

You cannot call the function directly, you need to send a message to the content script. Meaning something like that:

var worker = tabs.activeTab.attach({
  ...
});

// Some time later
worker.postMessage("doABC");

And in the content script:

self.on("message", function(message) {
  if (message == "doABC")
    abc();
});

For more information on communicating with content scripts see documentation .

According to documentation it should work this way;

However I have similar question Accessing pre-loaded content script from ActionButton not yet resolved.

// main.js
function handleClick(state) {
    var myWorker = tabs.activeTab.attach({

    });   
    myWorker.port.emit("initialize", "Message from the add-on");
}

// content.js
/*BEGIN Listen events coming from Add-on script*/
self.port.on("initialize", function () {
    alert('self.port.on("initialize")');
    return;   
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM