如何在我的 chrome 扩展中等待异步并调用 sendResponse?

问题描述

我的 background.js 是:

chrome.runtime.onMessageExternal.addListener(handleMessage);


port = chrome.runtime.connectNative('hostName');
port.onMessage.addListener(sendResponse);


function handleMessage(request,sender,sendResponse) {
    sendNativeMessage(request.message);
} 

function sendNativeMessage(message) {
    port.postMessage(message);
}

function sendResponse(message) {
    document.dispatchEvent(
        new CustomEvent('responsefromNM',{
            detail: message,})
     );
}

我有这样的问题。我从我的网页调用

const msg = {
   action: 'start'
};

chrome.runtime.sendMessage('myExtensionId',{message: msg},function(response) {
    console.log('got response: ',response);
});

这会触发 handleMessage 函数来触发将调用我的本机应用程序的 sendNativeMessage 函数。一段时间后,我的 Native Application 返回一个响应,并且我的回答触发了 sendResponse 函数。我想在我的 sendMessage 响应回调中得到这个答案(console.log('got response: ',response)。我想在 handleMessage 中调用这个 sendResponse,但我正在为此苦苦挣扎。

 document.addEventListener('responsefromNM',(res) => {
  ... call SendResponse in handleMessage ? 
});

怎么做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)