Bunker
Bunker

Reputation: 1051

Chrome extension webrequest redirect after executing code that takes 4/5 seconds

I'm trying to create a Chrome extension that executes some code (takes about 4 seconds) and afterwards does a callback that redirects the user to a page. However, no redirect takes place with the following code:

 chrome.webRequest.onBeforeRequest.addListener(function(details) {
    functionThatTakes4Seconds(function(){
            return {
                redirectUrl: redirect
            };
    );
}, {
    urls: ["url.com"]
}, ["blocking"]);

When I don't run the function that takes 4 seconds the redirect works:

 chrome.webRequest.onBeforeRequest.addListener(function(details) {
            return {
                redirectUrl: redirect
            };
}, {
    urls: ["url.com"]
}, ["blocking"]);

Does it timeout? Is there a workaround for this?

Upvotes: 0

Views: 350

Answers (1)

Xan
Xan

Reputation: 77521

You can't return from asynchronous code.

If you do return a blocking response, it must be returned synchronously; Chrome will not wait and you don't get a callback to call asynchronously.

If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.

E.g. if your code took 4 seconds to complete but was synchronous, you could return the value from it and do this:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
  return {
    redirectUrl: functionThatTakes4Seconds() // must return something
  };
}, {
    urls: ["url.com"]
}, ["blocking"]);

But you can't do an asynchronous call and have Chrome wait for it.

Compare to Messaging: there you get a callback sendResponse that you can potentially call asynchronously. But not here.

Upvotes: 2

Related Questions