简体   繁体   English

网址已保存在chrome.storage.local中的chrome.webRequest redirectUrl

[英]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. 我正在尝试拦截Web请求,并将其重定向到我保存在本地存储中的url,但无法正常工作。 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: 硬编码return语句/ url可以工作:

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. chrome.storage api是异步的 ,因此您在此处采用的方法无效。 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 在进行网络请求之前,请检查网址是否为http://myapp.com/theurl
  2. If it is, then make an asynchronous call to chrome.storage.local.get 如果是,则对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 chrome.storage.local.get调用中的代码(即return语句)不会立即执行,而是在以后的某个时间运行
  4. The rest of your code continues to run and nothing is returned from your webRequest listener 您的其余代码继续运行,并且webRequest侦听器未返回任何内容

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 ). 最简单的方法是在加载扩展程序时将本地存储的值存储在某个变量内(称其为storage_cache )。 Then from the webRequest listener you could say return { redirectUrl: storage_cache.savedUrl }; 然后,您可以从webRequest侦听器说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. 如果您的存储将经常更改,那么有比这更好的方法了……但是,无论选择哪种实现,要记住的关键是不要混淆同步和异步事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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