Synchronous call in Google Chrome extension Synchronous call in Google Chrome extension google-chrome google-chrome

Synchronous call in Google Chrome extension


Another answer on Stack Overflow recommends keeping track of the tabs outside of your listener function, which avoids this problem entirely.

Example code:

/*  * -------------------------------------------------- * Keep list of tabs outside of request callback * -------------------------------------------------- */var tabs = {};// Get all existing tabschrome.tabs.query({}, function(results) {    results.forEach(function(tab) {        tabs[tab.id] = tab;    });});// Create tab event listenersfunction onUpdatedListener(tabId, changeInfo, tab) {    tabs[tab.id] = tab;}function onRemovedListener(tabId) {    delete tabs[tabId];}// Subscribe to tab eventschrome.tabs.onUpdated.addListener(onUpdatedListener);chrome.tabs.onRemoved.addListener(onRemovedListener);/*  * -------------------------------------------------- * Request callback * -------------------------------------------------- */// Create request event listenerfunction onBeforeRequestListener(details) {    // *** Remember that tabId can be set to -1 ***    var tab = tabs[details.tabId];    // Respond to tab information}// Subscribe to request eventchrome.webRequest.onBeforeRequest.addListener(onBeforeRequestListener, {    urls: ["<all_urls>"],    types: ["main_frame"]}, ["blocking"]);


chrome.runtime.onMessage.addListener((message, rawSender, sendResponse) => {        // here, you can call sendResponse method in any where asynchronous.        return true;    // 这是重点,it's important    });// it also fit chrome.webRequest.onBeforeRequest.addListener

official document