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

梦想与她 提交于 2019-12-02 05:48:50

问题


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"]);

回答1:


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.



来源:https://stackoverflow.com/questions/24131029/chrome-webrequest-redirecturl-with-url-saved-in-chrome-storage-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!