我已经浏览了MDN上的webextension文档。我知道用于从content_script
到background script
进行通信的消息传递Api。但是,我想通过popup script to background script
进行沟通。
我的用例是:
如何从与
background script
页面相关联的脚本与popup.html
进行通信。
让我们说,manifest.json
是
{
"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是
<html>
<body>
<script src = 'popup.js'></script>
</body>
<html>
popup.js
我的问题就在这里。从以下选项中使用哪种方法:
browser.runtime.sendMessage({"actualMessage":"some message"});
或
var tabQ = browser.tabs.query({
currentWindow: true,
active: true
});
tabQ.then( (tabs)=>{
browser.tabs.sentMessage(tab[0].id , {'actualMessage' : "some message"});
});
答案 0 :(得分:0)
我的问题就在这里。从以下选项中使用哪种方法:
您使用browser.runtime.sendMessage({"actualMessage":"some message"});
答案 1 :(得分:0)
用于弹出脚本(与内容脚本相反-您可能会在主机标签窗口中运行的内容);
您只需将函数或变量放在后台脚本中,然后通过对后台window
对象的引用从弹出窗口中调用/设置/读取这些函数或变量。
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!") ;
}
然后您可以在弹出窗口中执行操作(使用异步/承诺)
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 ;
}