这样做:简单的消息传递,在onMessage监听器中没有嵌套调用chrome API。
content_script
chrome.runtime.sendMessage({ message: "what is my windowId?" }, function(response) {
// clearLocalStorage(response.allWindowsId);
windowId = response.windowId;
console.log(windowId);
});
BACKGROUND_SCRIPT
chrome.runtime.onMessage.addListener(function(request, sender,sendResponse) {
if (request.message === "buttonClick") {
chrome.tabs.reload(sender.tab.id);
sendResponse({message: 'handle button click'});
} else if (request.message === "what is my windowId?") {
sendResponse({
windowId: sender.tab.windowId
});
}
return;
});
这不起作用:在onMessage侦听器中嵌套调用qazxsw poi。
BACKGROUND_SCRIPT
chrome.windows.getAll
我也尝试使用chrome.runtime.onMessage.addListener(function(request, sender,sendResponse) {
if (request.message === "buttonClick") {
chrome.tabs.reload(sender.tab.id);
sendResponse({message: 'handle button click'});
} else if (request.message === "what is my windowId?") {
// additional code here
chrome.windows.getAll(function(windows) {
sendResponse({
windowId: sender.tab.windowId,
windows: windows
});
});
}
return;
});
调用chrome.windows.getAll异步,但没有运气。
以下是错误消息。似乎在onMessage函数返回后调用window.getAll,即使我已经通过最终返回标记了这个函数async;声明。
chromeExtensionAsync
我刚刚发布了一个OSS库来帮助解决这个问题:Error handling response: TypeError: Cannot read property 'windowId' of undefined
Unchecked runtime.lastError: The message port closed before a response was received.
看看BrowserExtensionTransport。它包括在内容脚本和后台窗口之间进行远程调用的示例。