Google Chrome 扩展程序消息传递问题:
在此 Chrome 扩展程序中
我的弹出页面:
chrome.browserAction.onClicked.addListener(getMessage);
getMessage();
function getMessage()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});//getting response from content script
});
}
我的脚本页面:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({});
});
我没有从内容脚本得到任何响应。
编辑:
根据@serg,我已将代码移至后台页面。但仍然不起作用
最佳答案
如果您将弹出页面附加到浏览器操作按钮,则无法使用 chrome.browserAction.onClicked
监听器,它将不会触发。
- 删除弹出窗口,仅保留按钮
- 将所有内容移至后台页面。
- 将
tab.id
替换为null
。 - 删除开头的
createFile();
调用,因为在这种情况下它不会执行任何操作(内容脚本尚未准备好监听)。 - 不要使用警报来调试扩展,请使用
console.log()
。
关于javascript - Chrome 扩展程序中从内容脚本到后台页面的消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691465/