简体   繁体   中英

firefox webextension messaging from popup script to background script

I have been through the webextension documentation on MDN. I do know the Messaging Api used to communicate from content_script to background script . However, I want to communicate from popup script to background script .

My use case is:

How to communicate to background script from a script associated to popup.html page.

Let's say , manifest.json is

  {

   "description": "Demonstrating toolbar buttons",
   "manifest_version": 2,
   "name": "button-demo",
   "version": "1.0",
   "permissions" : ["activeTab","currentWindow"],//
   
   "background": {
        "scripts": ["background.js"]
    },

   "browser_action": {
   "browser_style": true,
   "default_popup": "popup.html",
   "default_icon": {
   "16": "icons/page-16.png",
   "32": "icons/page-32.png"
   }
 }
}

background.js

//background script is listening to 
browser.runtime.onMessage.addListener((sentMesssage) => 
{ 
    console.log('got the message: ',sentMessage.actualMessage);
});

popup.html is

   <html>
   <body>
     <script src = 'popup.js'></script>
   </body>
   <html>
   
   

popup.js

My question stands here. Which method to use from the below options:

 browser.runtime.sendMessage({"actualMessage":"some message"});

OR

var tabQ = browser.tabs.query({
   currentWindow: true,
   active: true
});

tabQ.then( (tabs)=>{
 browser.tabs.sentMessage(tab[0].id , {'actualMessage' : "some message"});
});

My question stands here. Which method to use from the below options:

You use browser.runtime.sendMessage({"actualMessage":"some message"});

For a popup script (as opposed to content script - the thing you might run in the host tab window) ;

You can just put functions or variables in the background script and call/set/read those from the popup via a ref to the background window object.

background-script.js

let item = null ; //private to background script
function setItem(i){item = i;}
function getItem(){return item;}
var anotherItem ; // publicly available on background window object

var popUpEar ; // if you need to initiate communication from background - set in popup

function talkToPopUp(){
    popUpEar("listen to this!") ;
}

then in your popup you can do (using async/Promises)

function earToTheBackground(msg){
    console.log(msg);
}
async function f(){
    let backgroundWindow  = await browser.runtime.getBackgroundPage();

    let local_item = backgroundWindow.getItem();
    backgroundWindow.setItem("something else");
    let local_anotherItem = backgroundWindow.anotherItem ;
    backgroundWindow.anotherItem = "something else again";

    backgroundWindow.popUpEar = earToTheBackground ;
}

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