Return true from onMessage listener 保持响应通道打开,然后从 chrome API 回调中调用 sendResponse。请注意,chrome API 回调始终运行 asynchronously,即在 main 函数完成后。
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
let callbackCounter = 2;
chrome.tabs.update(sender.tab.id, {active: true}, function (tab) {
// this callback runs after the parent function has finished
if (--callbackCounter === 0) {
sendResponse({foo: 'bar'});
}
});
chrome.windows.update(sender.tab.windowId, {focused: true}, function (window) {
// this callback runs after the parent function has finished
if (--callbackCounter === 0) {
sendResponse({foo: 'bar'});
}
});
// keep the response channel open
return true;
});
在现代浏览器中,这通常通过 Promise API 解决。
您可以通过加载 Mozilla WebExtension polyfill 将其与 Chrome API 一起使用。
browser.runtime.onMessage.addListener((request, sender) => {
return Promise.all([
browser.tabs.update(sender.tab.id, {active: true}),
browser.windows.update(sender.tab.windowId, {focused: true}),
]).then(() => {
// .........
return {foo: 'bar'};
});
});
polyfill 还允许您使用 await/async 语法:
browser.runtime.onMessage.addListener(async (request, sender) => {
await Promise.all([
browser.tabs.update(sender.tab.id, {active: true}),
browser.windows.update(sender.tab.windowId, {focused: true}),
]);
return {foo: 'bar'};
});