Chrome Extension error: “Unchecked runtime.lastError while running browserAction.setIcon: No tab with id”

烈酒焚心 提交于 2019-11-30 07:58:00

问题


I'm coding my Google Chrome Extension where I set the app's icon from the background script as such:

try
{
    objIcon = {
        "19": "images/icon19.png",
        "38": "images/icon38.png"
    };

    chrome.browserAction.setIcon({
        path: objIcon,
        tabId: nTabID

    });
}
catch(e)
{
}

Note that I wrapped the call in try/catch block.

Still, sometimes I'm getting the following message in the console log:

Unchecked runtime.lastError while running browserAction.setIcon: No tab with id: 11618.

It's hard to debug this error because it seems to come up only when I close or reload the Chrome tab, it doesn't have a line number or any info for me to track, plus it's not easy to run through a debugger (i.e. I cannot set a break-point on the moment when error occurs, but if I blindly set a break-point on the chrome.browserAction.setIcon() line, I don't see the message in the log anymore.)

So I'm curious if anyone could suggest how to remedy this error?

EDIT: Just to post an update. I am still unable to resolve this issue. The suggestion proposed by @abraham below offers a somewhat working approach, but it is not fail safe. For instance, in a situation when the tab is closing I may call his suggested chrome.browserAction.setIcon() that may succeed if the tab is not yet closed, but while within its callback function the tab may eventually close and thus any consecutive calls to some other API that requires that same tab ID, say setBadgeBackgroundColor() may still give me that same No tab with id exception. In other words, for those who know native programming, this is a classic race condition situation. And I'm not sure if it's a bug in Chrome, because obviously JS does not offer any thread synchronization methods...

I've witnessed this behavior several times while doing my tests. It doesn't happen often because we're talking about very precise timing situation, but it does happen. So if anyone finds a solution, please post it below.


回答1:


Include a callback and check chrome.runtime.lastError.

objIcon = {
    "19": "images/icon19.png",
    "38": "images/icon38.png"
};

function callback() {
    if (chrome.runtime.lastError) {
        console.log(chrome.runtime.lastError.message);
    } else {
        // Tab exists
    }
}

chrome.browserAction.setIcon({
    path: objIcon,
    tabId: nTabID

}, callback);


来源:https://stackoverflow.com/questions/25735050/chrome-extension-error-unchecked-runtime-lasterror-while-running-browseraction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!