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.
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);