简体   繁体   中英

chrome.webRequest redirectUrl with URL Saved in chrome.storage.local

I'm trying to intercept web requests and redirect them to a url I have saved on local storage but it isn't working. My code is as follows:

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        if (details.url === 'http://myapp.com/theurl') {
            chrome.storage.local.get("http://myapp.com/theurl", function (result) {
                return { redirectUrl: result.savedUrl }; //savedUrl property is the modified Url
            });
        }
    }, { urls: ["<all_urls>"] }, ["blocking"]);

Hardcoding the return statement/url works:

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        if (details.url === 'http://myapp.com/theurl') {
                return { returnUrl : 'http://myapp.com/modifiedurl' };
            });
        }
    }, { urls: ["<all_urls>"] }, ["blocking"]);

The chrome.storage api is asynchronous , so the approach that you are taking here will not work. The basic run-through of what is happening with the code you have is:

  1. Before the webrequest, check if the url is http://myapp.com/theurl
  2. If it is, then make an asynchronous call to chrome.storage.local.get
  3. The code inside your chrome.storage.local.get call (ie. the return statement) is not executed immediately and will be run at some later time
  4. The rest of your code continues to run and nothing is returned from your webRequest listener

There are a couple of ways that you can make this work. The easiest would be to store the values of the local storage inside some variable when your extension is loaded (call it, say, storage_cache ). Then from the webRequest listener you could say return { redirectUrl: storage_cache.savedUrl };

If your storage will change frequently then there are better approaches than this one...but the key thing to remember for whatever implementation your choose is to not to mix up synchronous and asynchronous events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM