gpt4 book ai didi

javascript - onMessageExternal.addListener 的回调可以是异步的吗?

转载 作者:行者123 更新时间:2023-12-03 02:26:00 26 4
gpt4 key购买 nike

我有一个 Chrome 扩展程序和一个简单的网页一起运行。我向扩展程序发送一条消息,此时扩展程序会执行一些异步操作。下面的代码不起作用,因为 sendMessage 上的回调在我的 promise 解决之前立即触发。有没有办法解决?或者我是否需要手动将消息从扩展发送回浏览器?

网页:

chrome.runtime.sendMessage(editorExtensionId, {action: "share"}, function(response) {
console.log(response);
// var promise = navigator.mediaDevices.getUserMedia({audio:true, video:true});
});

扩展名:

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
var promise = new Promise((resolve, reject) => {
if (request.action === 'share') {
chrome.desktopCapture.chooseDesktopMedia(["screen","window"], (streamId, options) =>{
resolve(streamId);
});
} else {
reject('Bad action');
}
}).then(resp => {
sendResponse(resp);
});
});

最佳答案

根据documentationsendResponse 函数

becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called)

因此,您的扩展代码将类似于:

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
var promise = new Promise((resolve, reject) => {
if (request.action === 'share') {
chrome.desktopCapture.chooseDesktopMedia(["screen","window"], (streamId, options) =>{
resolve(streamId);
});
} else {
reject('Bad action');
}
}).then(resp => {
sendResponse(resp);
});

return true; //<-- add this

});

关于javascript - onMessageExternal.addListener 的回调可以是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48937439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com