Это работает : простая передача сообщений без вложенного вызова API chrome в onMessage слушателе.
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;
});
Это не работает : вложенный вызов chrome.windows.getAll в прослушивателе onMessage.
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?") {
// additional code here
chrome.windows.getAll(function(windows) {
sendResponse({
windowId: sender.tab.windowId,
windows: windows
});
});
}
return;
});
Я также пытался сделать вызов chrome.windows.getAll асинхронно, используя chromeExtensionAsync , но пока не повезло.
Ниже приведено сообщение об ошибке. Похоже, что вызов window.getAll происходит после возврата функции onMessage , хотя я пометил эту функцию асинхронной с помощью окончательного return; оператора.
Error handling response: TypeError: Cannot read property 'windowId' of undefined
Unchecked runtime.lastError: The message port closed before a response was received.