chrome扩展addListener和sendMessage同步使用

时间:2017-05-18 07:56:02

标签: javascript asynchronous google-chrome-extension

我需要通过内容脚本等待来自DOM的信息,并在后台脚本的监听器中使用它。

我想同步运行此代码但遇到异步问题,侦听器在getFilename函数返回之前调用suggest如何同步运行?

background.js

function getFilename(AAA, fn) {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {data: AAA.text }, function(response) {
                appendfn = response.data || "SRTING";
                fn = fn.replace(..., '-' + appendfn);
                return fn; // this is correct
            });
        });
}


chrome.downloads.onDeterminingFilename.addListener(function(downloadItem, suggest) {
    if (downloadItem.url.substr(...) == "DOMAIN") {
        var appendfn = "";
        var fn = downloadItem.filename;

        fn = getFilename(downloadItem, fn); // why doesn't this block? is it because suggest is used as a callback?

        console.log(fn); // undefined  
        suggest({filename : fn})
    }
});

content.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
   var elm = document.querySelectorAll(... msg.data);
   sendResponse({data: elm.text});
});

要问的正确问题不是:如何同步运行,而是如何让它以异步方式运行?如此框架的答案很简单。

1 个答案:

答案 0 :(得分:0)

让事情变得复杂 - 我只需要在return true的末尾addListener启用suggest的异步调用。

如果你有一个优雅的Javascript-y解决方案,请分享:)