chrome.runtime.onMessage response with async await

后端 未结 4 1805
闹比i
闹比i 2021-02-05 04:03

I want to use async await in an onMessage listener:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey(         


        
4条回答
  •  旧巷少年郎
    2021-02-05 04:35

    Honestly, it looks like Google Chrome Extensions don't support the await keyword. I've successfully used asynchronous chrome.runtime.onMessage.addListener's before, and every time I try to use await I see this syntax error in the Chrome Debugging Tools, on the line that I use await:

    Here's how I've been testing:

    I created a very basic listener:

    chrome.runtime.onMessage.addListener(function(data, MessageSender, sendResponse) {
        sendResponse(awaitTester);
        var async = true;
    
        // returns true if asyncronous is needed
        if (async) return true;
    });
    

    my awaitTester function looks like this:

    function awaitTester() {
        var prom = new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve('test');
            }, 4000);
        });
    
        var awaited = await prom;
        return awaited;
    }
    

    finally, my message sender is what you'd expect:

    chrome.runtime.sendMessage({}, function(message) {
        debugger;
        console.log(message);
    });
    

    And in the debugger / console I always get undefined.

提交回复
热议问题