Search code examples
google-chrome-extensionchrome-extension-manifest-v3

Unchecked runtime.lastError: No tab with <id>, Chrome Extension


I don't understand why i recieve this error

Error

This code works

chrome.tabs.onUpdated.addListener(handleUrls);

function handleUrls(tabId, { changeInfo }, tab) {

    const isOauthTokenPage = tab.url?.match(CONFIG.OAUTH_TOKEN_PAGE_PATTERN);

    if (isOauthTokenPage) {
        chrome.tabs.remove(tabId);
    }
}

But why i get this error?

I tried chrome.tabs.onUpdated.removeListener before and after chrome.tabs.remove(tabId), tried chrome.tabs.query to get "actual" tabId


Solution

  • So it's trigger more than once

    To avoid it

    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
        // check url state
        if (!changeInfo.url) return;
        
        // your code...
        if ((tab.url).match(CONFIG.OAUTH_TOKEN_PAGE_PATTERN)) {
            // won't invoke onUpdated several times
            chrome.tabs.remove(tabId);
        }
    });