我知道它已经在这里出现了数千次,但我现在被困住了。我读了很多答案并研究了 code.google.com 但没有成功。我正在尝试在 Chrome 扩展程序中从 background.html
发送请求到 contentscript.js
。不过,我设法以另一种方式让它工作。
background.html
内的代码:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
contentscript.js
内的代码:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({farewell: "nope"});
});
manifest.json
应该没问题,因为通信正在向后工作,并且其他任何内容都正常工作。谢谢!
最佳答案
你的代码是好的,你的触发器一定有问题。我使用您的代码创建了一个简单的扩展并且它有效。将这两个位添加到您的背景和内容脚本中。然后在任意页面上输入人民币并选择“发送消息”。您应该会收到警报。
背景.html
var menuid = chrome.contextMenus.create({"title":"Send Message", "onclick": SendMessage, "documentUrlPatterns":["http://*/*"]});
function SendMessage() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
}
内容脚本
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello") {
alert('hello');
sendResponse({farewell: "goodbye"});
}
else
{
alert('goodbye');
sendResponse({farewell: "nope"});
}
});
关于javascript - 卡在消息传递background.html >> contentscript.js(chrome扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858730/