Reputation: 4800
I am making a chrome extension that blocks specific sites added to local storage through popup window. I think the problem in this code is, it returns before completion of chrome.storage.local.get's callback. How can I make it wait for sometime before returning ?
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var matched = false;
chrome.storage.local.get ( 'blocked_sites', function ( sites ) {
var bsites = sites.blocked_sites;
for ( i = 0, size = bsites.length; i < size; i++ ) {
if ( details.url.indexOf( "://" + bsites[i] + "/" ) != -1 ) {
matched = true;
} // end if
} // end for
});
// WAIT HERE FOR VALUE OF MATCHED TO BE SET BY CALLBACK
return { cancel: matched };
},
{ urls: ["<all_urls>"] },
["blocking"] );
chrome.storage.local.set({'blocked_sites': [ 'www.topnotchdev.com'] }, null);
Upvotes: 0
Views: 159
Reputation: 1337
With the way your code structured you won't be able to make return { cancel: matched };
execute after the callback. The reason is because return { cancel: matched };
is run in one execution frame ( the same that calls chrome.storage.local.get
) and the callback is run in some future execution frame. When you call asynchronous method it can only insert the callback into event loop for some future time, by the time that callback is executed return { cancel: matched };
is already executed.
Upvotes: 0
Reputation: 77571
You can't call any asynchronous function in webRequest
blocking listeners. There is no way around it, hacky or otherwise. It is fundamentally impossible, since JavaScript is single-threaded; an async operation won't even start before the current function finishes executing.
This means you cannot rely on asynchronous storage; you must have a local synchronous cache for it.
Save blocked_sites
to a variable, and update it on chrome.storage.onChanged
event. This way, you'll have a synchronous cache of the setting.
Upvotes: 2