Sudden error in Chrome extension: "cannot access before initialization"

Viewed 451

In Chrome extension to catch activated or updated tab and get an url from them i use a construction like

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) run(tab);
});

chrome.tabs.onActivated.addListener(info => {
    chrome.tabs.get(info.tabId, run);
});

const processingTabId = {};

function run(tab) {
    if (processingTabId[tab.id]) return;
    processingTabId[tab.id] = true;

    let newUrl = new URL(tab.pendingUrl || tab.url)
    currentHost = newUrl.host;

Some days it worked like a charm, and this extension was in use. But today, without Chrome update or any code change, i suddenly realize, that i get no url under no circumstances, not on tab activation, not on tab update (refresh). Looking into extension backend i realized an error, which was never there:

Cannot access 'processingTabId' before initialization

and these code lines were marked:

function run(tab) {
    if (processingTabId[tab.id]) return;

Do somebody know, what this error means, how it is to fix and why it happens so suddenly?

1 Answers

You need to initialize processingTabId before you call the run() function that uses it. So put the declaration at the top, before adding the listeners that call run().

const processingTabId = {};

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) run(tab);
});

chrome.tabs.onActivated.addListener(info => {
    chrome.tabs.get(info.tabId, run);
});

function run(tab) {
    if (processingTabId[tab.id]) return;
    processingTabId[tab.id] = true;

    let newUrl = new URL(tab.pendingUrl || tab.url)
    currentHost = newUrl.host;
Related