Reputation: 123
I am trying to open a window by Chrome extension by browser action.
var wid = null;
chrome.windows.get(wid, function(chromeWin) {
chrome.windows.create({'url': 'https://google.com'}, function(chromeWin) {
wid = chromeWin.id;
}
);
});
To prevent multiple copies of the Window, I am trying to check window id. But if used first time, understandably, it throws error because wid
is null
.
Error: Invocation of form windows.get(null, function) doesn't match definition windows.get(integer windowId, optional object getInfo, function callback)
I tried to use try..catch
block and in catch I am handling "wid
is null
" case.
try {
var wid = null;
chrome.windows.get(wid, function(chromeWin) {
chrome.windows.create({'url': 'https://google.com'}, function(chromeWin) {
wid = chromeWin.id;
}
);
});
}
catch(error) {
chrome.windows.create({'url': 'https://google.com'}, function(chromeWin) {
wid = chromeWin.id;
}
);
}
But try..catch
is not catching the "wid
is null
" case. I know if
clause may help for my experiment but I want to learn why try
behaves this way.
Why is try..catch
not caching the error and how can I open windows without copies in Chrome?
Upvotes: 4
Views: 3260
Reputation: 77531
The answer is actually going to be rather boring: it does work for call-validation performed by Chrome API, since that happens synchronously:
try {
var wid = null;
chrome.windows.get(wid, function(chromeWin) {
console.log("This should never be visible.");
});
} catch(e) {
console.log("Error caught!");
console.warn(e);
}
This catches the error (and shows it as a warning instead). So your original problem must be elsewhere (another part of code, not reloading the code properly, something like that).
My original point was that some errors happen inside Chrome's async processing. This is not this error, but rather errors reported with chrome.runtime.lastError
. If you do not check that value, and there is an error, it raises an exception that cannot be caught, because it happens after the original invocation and outside your callback.
More information about that here, but again, that does not apply in your case.
Upvotes: 3