I know that waiting for an asynchronous method is stupid, one should use callbacks instead. But what if an third party API forces you to be synchronous?
I'm developing a Chrome Extension that will prevent the user from visiting websites that's already open in another tab. I basically need to cancel requests based on the urls in open tabs. I want to use chrome.webRequest.onBeforeRequest like this:
function onBeforeRequest(details) {
var websiteAlreadyOpenInOtherTab;
// Here i want to set `websiteAlreadyOpenInOtherTab` by using the `chrome.tabs`
// API. It's asynchronous though and that's my problem. I cant return a value
// from an asynchronous method call.
if (websiteAlreadyOpenInOtherTab) {
return { cancel: true };
}
}
chrome.webRequest.onBeforeRequest.addListener(
onBeforeRequest,
{ urls: ['<all_urls>'], types: ['main_frame'] },
['blocking']);
Hopefully you see my dilemma in the code above. I need to return an object based on the result of asynchronous method calls. Is it possible to achieve this?
chrome.tabschanges and havewebsiteAlreadyOpenInOtherTabalready containing the right value whenonBeforeRequestis called?onBeforeRequestcan't contain the right value (because I won't know it beforeonBeforeRequestis called. But I could maintain some kind of structure that knows about open tabs. It's a walk-around alright. @davin +1 on @Bergi's arguments. It's unacceptable to send a request and close the tab in my use case. The request should be canceled. But thanks for your suggestion anyway. :)