encore2097
encore2097

Reputation: 503

chrome extension addListener and sendMessage synchronous usage

I need to wait for information from the DOM via the content script and use that in the listener in the background script.

I'd like to run this code synchronously but running into async issues, the listener calls suggest before the getFilename function returns. How do I run this synchronously?

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});
});

The correct question to ask is not: how do I run this synchronously, rather how can I get it to work asynchronously? When framed like that the answer is simple.

Upvotes: 0

Views: 1041

Answers (1)

encore2097
encore2097

Reputation: 503

Was over complicating things -- all I had to do was return true at the end of the addListener to enable async call of suggest.

If you have an elegant Javascript-y solution, please share :)

Upvotes: 1

Related Questions