我正在开发一个Chrome扩展程序。我有一个内容脚本和一个事件页面。从内容脚本中,我使用chrome.runtime.sendMessage()向事件页发送消息。在事件页面上,我使用onMessage事件侦听器发送回响应--但是,在chrome检测到文件已开始下载后,我想发送此响应。
contentScript.js
window.location.href = download_link; //redirecting to download a file
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
eventPage.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
chrome.downloads.onCreated.addListener(function(DownloadItem downloadItem) {
sendResponse({farewell: "goodbye"});
return true;
});
});
现在,我还没有尝试过chrome.downloads.onCreated侦听器,但我假设这是正确的语法。但是,代码不起作用,控制台正在返回此错误:
Error in event handler for (unknown): Cannot read property 'farewell' of undefined
Stack trace: TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://dlkbhmbjncfpnmfgmpbmdfjocjbflmbj/ytmp3.js:59:31
at disconnectListener (extensions::messaging:335:9)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at EventImpl.dispatchToListener (extensions::event_bindings:395:22)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:65:26)
at EventImpl.dispatch_ (extensions::event_bindings:378:35)
at EventImpl.dispatch (extensions::event_bindings:401:17)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.publicClass.(anonymous function) [as dispatch] (extensions::utils:65:26)
在没有chrome.downloads.onCreated侦听器的情况下,我尝试了这一点,并且它可以工作,响应由内容脚本获取。我在网上读到,您需要添加返回true;才能使它工作,但它不适合我。我怀疑这是因为第二个事件侦听器,它输入了一个新的作用域,这意味着不能从那里调用sendResponse --如果是这样的话,我如何调用sendResponse函数?
发布于 2014-06-04 06:26:42
你从错误的地方来的return true;
。
该申报表的目的的意思是说“我还没有给sendResponse
打电话,但我会打的”。
但是,您正在从onCreated
回调中返回它--到那时已经太晚了,因为在添加了侦听器之后,您的原始onMessage
处理程序就终止了。你只需要移动线:
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
chrome.downloads.onCreated.addListener( function(DownloadItem downloadItem) {
sendResponse({farewell: "goodbye"});
});
return true;
});
https://stackoverflow.com/questions/24027618
复制相似问题