Chrome v64。
我想从content.js向popup.js发送消息
我设法从popup.js向content.js发送了一条消息。但是如何以相反的方式完成呢?我还下载了一个示例扩展,它也不起作用。
我必须添加特殊权限吗?我尝试了一次消息和长时间运行的消息通道。
权限:
"permissions": [
"background",
"tabs",
"activeTab",
"storage",
"webRequest",
Content.js
chrome.runtime.sendMessage({
data: "mauzen"
}, function (response) {
return true;
});
debugger;
var port = chrome.runtime.connect({
name: "knockknock"
});
port.postMessage({
joke: "Knock knock"
});
port.onMessage.addListener(function (msg) {
debugger;
if (msg.question == "Who's there?")
port.postMessage({
answer: "Madame"
});
else if (msg.question == "Madame who?")
port.postMessage({
answer: "Madame... Bovary"
});
});
后台.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
sendResponse({
data: "background"
});
if (request.data === "success") {
alert("success");
} else {
//alert(request.data);
}
});
console.assert(port.name == "knockknock");
port.onMessage.addListener(function (msg) {
if (msg.joke == "Knock knock")
port.postMessage({
question: "Who's there?"
});
else if (msg.answer == "Madame")
port.postMessage({
question: "Madame who?"
});
else {
port.postMessage({
question: "background"
});
}
});
Popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "popup"
});
if (message.data === "success") {
alert("success");
} else {
// alert(message.data);
}
});
chrome.runtime.onConnect.addListener(function (port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function (msg) {
if (msg.joke == "Knock knock")
port.postMessage({
question: "Who's there?"
});
else if (msg.answer == "Madame")
port.postMessage({
question: "Madame who?"
});
else {
port.postMessage({
question: "popup"
});
}
});
});
2条答案
按热度按时间a0zr77ik1#
这是我发现的,测试了一下。
要从content.js脚本向弹出窗口发送消息,请执行以下操作:
和在你的popup.js:
只有当您的Popup处于活动状态(=打开)时,才会收到content.js发送给popup.js的消息
,即您点击工具栏中的page_action(browser_action)图标,弹出窗口出现,然后它处于打开/活动状态。只有这样,它才能发送和接收消息!
**弹出示例:**x1c 0d1x
你可以这样测试
将以下脚本放入您的content.js中:
并在您的popup.js**:**
只要执行
setInterval
,您可以单击扩展图标,打开弹出窗口,然后它将显示警报。ui7jx7zq2#
从你的代码中看起来,你正在从你的内容脚本向后台和弹出脚本发送一条消息,这与你所描述的相反。
从扩展发送消息到内容脚本需要使用
chrome.tabs.sendMessage
,请参阅https://developer.chrome.com/apps/messaging