Unable to check runtime.lastError during browserAction.setBadgeText

前端 未结 3 436
眼角桃花
眼角桃花 2020-12-11 22:45

chrome.browserAction.setBadgeText(object details) is used to set the badge text for a chrome extension. However, if the tabId doesn\'t exist, Chrome produces the following e

3条回答
  •  猫巷女王i
    2020-12-11 23:23

    An option would be to call chrome.tabs.get first and if no error is called assume that the tab will exist for the next few milliseconds.

    var tabId = 5000;
    function callback(tab) {
        if (chrome.runtime.lastError) {
            console.log(chrome.runtime.lastError.message);
        } else {
            chrome.browserAction.setBadgeText({
                text: 'text',
                tabId: tabId
            });
        }
    }
    chrome.tabs.get(tabId, callback);
    

    There is of course always a chance the tab could get closed between tabs.get finishing and setBadgeText getting called but it's very unlikely.

提交回复
热议问题