使用chrome.downloads传递消息

时间:2014-06-04 01:30:10

标签: google-chrome-extension

我正在开发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侦听器的情况下尝试了这个并且它可以正常工作,内容脚本会提取响应。我在网上看到你需要添加 return true; 以使其正常工作,但它对我不起作用。我怀疑它是因为第二个事件监听器,它进入一个新的范围意味着无法从那里调用sendResponse - 如果是这样的话,我该如何调用sendResponse函数?

1 个答案:

答案 0 :(得分:0)

return true;来自错误的地方。

purpose of that return是说“我还没有打电话给sendResponse,但我要去”。

但是,你是从onCreated回调中返回的 - 到那时已经太晚了,因为在添加了监听器之后,你的原始onMessage处理程序就会终止。你只需要移动这条线:

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    chrome.downloads.onCreated.addListener( function(DownloadItem downloadItem) {
        sendResponse({farewell: "goodbye"});
    });
    return true;
});