【发布时间】:2014-10-10 09:30:00
【问题描述】:
我正在尝试应用以下流程:
绑定background.js 中的键,当按下它们时:
从background.js -> contentScript.js发送消息
发送来自contentScript.js -> background.js的响应
这是menifit.json 的定义:
"background" : {
"scripts" : ["background.js"],
"persistent" : true
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["contentScript.js"]
}
],
绑定部分工作正常。
这是background.js中的代码:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
这是contentScript.js中的代码:
chrome.runtime.onMessage.addListener(HandleMessage);
function HandleMessage(request, sender, sendResponse)
{
if (request.greeting == "hello")
{
sendResponse({farewell: "goodbye"});
}
};
这是我得到的错误:
Error in event handler for (unknown): Cannot read property 'farewell' of undefined
Stack trace: TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://fejkdlpdejnjkmaeadiclinbijnjoeei/background.js:64:26
at disconnectListener (extensions::messaging:338:9)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at EventImpl.dispatchToListener (extensions::event_bindings:397:22)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:93:26)
at EventImpl.dispatch_ (extensions::event_bindings:379:35)
at EventImpl.dispatch (extensions::event_bindings:403:17)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.publicClass.(anonymous function) [as dispatch] (extensions::utils:93:26)
万一发生变化
console.log(response.farewell);
到
console.log("OK");
它工作正常,但那样我无法从contentScript.js 获取值
我应该改变什么?
【问题讨论】:
-
应该编辑问题以说明它是关于 Chrome 扩展程序,而不是 Chrome 应用程序。我已经删除了 google-chrome-app 标签。
标签: javascript jquery google-chrome google-chrome-extension