作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Chrome v64。
我想从 content.js 向 popup.js 发送消息。
我设法从 popup.js 向 content.js 发送消息。但是如何以相反的方式做到这一点?我还下载了一个示例扩展,它也不起作用。
我必须添加特殊权限吗?
我尝试了一次消息传递和长时间运行的消息 channel 。
权限:
"permissions": [
"background",
"tabs",
"activeTab",
"storage",
"webRequest",
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"
});
});
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"
});
}
});
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"
});
}
});
});
最佳答案
这是我发现的,测试了一下。
发送消息 来自 content.js 脚本到您的弹出窗口,您可以执行以下操作:
chrome.runtime.sendMessage({
data: "Hello popup, how are you"
}, function (response) {
console.dir(response);
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "I am fine, thank you. How is life in the background?"
});
});
var timer = 0;
var si = setInterval(() => {
try {
chrome.runtime.sendMessage({
data: "Hello popup, how are you"
}, function (response) {
console.dir(response);
});
timer++;
if (timer === 5) {
clearInterval(si);
}
} catch (error) {
// debugger;
console.log(error);
}
}, 2000);
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
alert("I am popup!");
sendResponse({
data: "I am fine, thank you. How is life in the background?"
});
});
setInterval
执行你可以点击你的扩展图标,打开弹出窗口,然后它会显示一个警报。
关于google-chrome - Chrome 扩展 : How to send message from content. js 到 popup.js - Page_Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48620183/
我是一名优秀的程序员,十分优秀!