我正在开发一个谷歌浏览器扩展程序。我的目的是将消息从我的 script1.js 发送到 script2.js。这是我在 manifest.json 中写的:
{
"matches": ["https://www.google.fr/"],
"css": ["styles.css"],
"js": ["script1.js"]
},
{
"matches": ["my_website.html"],
"css": ["styles.css"],
"js": ["script2.js"]
},
这是我在 script1.js 中写的:
chrome.runtime.sendMessage('hello world!!!!!!');
在 script2.js 中:
chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){
alert(response);
} );
我认为我的做法不对,我想我必须使用 background.js,但我不知道该怎么做。
非常感谢。
最佳答案
正如您所说,您必须使用后台脚本。例如:
脚本1:
chrome.runtime.sendMessage({from:"script1",message:"hello!"});
背景.js
var tab2id;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.from == "script2") {
tab2id = sender.tab.id;
}
if (message.from == "script1"){
chrome.tabs.sendMessage(tab2id,message);
}
});
脚本2.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
alert("Script1 says: " + message.message);
});
chrome.runtime.sendMessage({from:"script2"});
请记住在 list 中包含您的后台脚本:
"background": {
"scripts": ["background.js"]
}
关于javascript - 将消息从内容脚本发送到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313507/