【发布时间】:2018-04-10 19:38:05
【问题描述】:
您好,我是 chrome 扩展的新手,我正在尝试进行扩展。我希望每次用户转到另一个选项卡时 background.js 向 content.js 发送请求,为此我在 background.js 中有这段代码
chrome.tabs.onActivated.addListener(function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "update"}, function(response) {
console.log(response.proto);
});
});
});
在 content.js 中我有这个代码来接收请求并发送响应:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.greeting);
var protocol = window.location.protocol;
sendResponse({ proto: protocol });
}
);
我在后台控制台中收到此错误:
Error in event handler for (unknown): TypeError: Cannot read property 'proto' of undefined
at background.js:6:32
我在普通控制台中没有收到任何错误。我已经使用了这个文档:
https://developer.chrome.com/apps/messaging
和
https://developer.chrome.com/extensions/tabs#event-onActivated
我做错了什么?
【问题讨论】:
标签: javascript google-chrome google-chrome-extension