Chrome 扩展异步消息传递

问题描述

我目前正在开发 Chrome 扩展程序,我想执行以下操作。

content.js:

chrome.runtime.sendMessage({message: "Teszt",licenseKey: "XXXX-XXXX-XXXX-XXXX",data: "bolond"},(response) => {
        alert(response.data);
});

background.js:

chrome.runtime.onMessage.addListener((request,sender,sendResponse) => {
    if(request) {

        const xhr = new XMLHttpRequest();
        xhr.open("GET",`https://api.hyper.co/v4/licenses/${request.licenseKey}`);
        xhr.setRequestHeader("Authorization",`Bearer publickey`)

        xhr.onload = () => {
            sendResponse({ sender: "background.js",data: (request.data+" response")  })
        }

        xhr.send();
    }
});

它不返回任何东西,显然是因为请求需要时间来完成。 我怎样才能使它异步?或者至少如何让 content.js 等到后台真正返回一些东西?

先谢谢你!

解决方法

请查看以下文档中的 simple one-time requests 部分 https://developer.chrome.com/docs/extensions/mv3/messaging/

如果要异步使用sendResponse,添加return true;到 onMessage 事件处理程序。

请尝试以下代码。它应该工作

    chrome.runtime.onMessage.addListener((request,sender,sendResponse) => {
    if(request) {

        const xhr = new XMLHttpRequest();
        xhr.open("GET",`https://api.hyper.co/v4/licenses/${request.licenseKey}`);
        xhr.setRequestHeader("Authorization",`Bearer publickey`)

        xhr.onload = () => {
            sendResponse({ sender: "background.js",data: (request.data+" response")  })
        }

        xhr.send();
        return true;
    }
});