【问题标题】:Redirect to new URL using onBeforeRequest and chrome.tabs.query (Chrome Extension)使用 onBeforeRequest 和 chrome.tabs.query(Chrome 扩展程序)重定向到新 URL
【发布时间】:2017-01-25 16:21:29
【问题描述】:

好时光。

我有一些有趣的想法,在用户输入推送“enter”后必须更改 URL。

我的清单文件:

 {
  "name": "The Pirate Bay_2",
  "description": "Redirect The Pirate Bay to a different host",
  "version": "1.0",
  "manifest_version": 2,

  "browser_action": {
        "default_title": "Saving Studio generator",
        "default_popup": "popup.html"

    },
    "background": {"scripts":["redirect.js"]},
    "content_scripts": [
   {
     "matches": ["http://*/*", "https://*/*"],
     "js": ["background.js"]
   }
   ],
  "permissions": 
  [ 
    "webRequest", 
    "https://www.amazon.com/", 
    "webRequestBlocking",
    "tabs",
    "activeTab"
    ]

}

我的 redirect.js 文件:

var host = "https://2ch.hk/b/";

chrome.tabs.query({
    'active': true, 'currentWindow': true
    }, function (tabs) {
    var url = tabs[0].url;
    host = host+url;
    console.log(url);
    });

chrome.webRequest.onBeforeRequest.addListener(  
    function(details) {

        if (localStorage.check_box == "true"){
            console.log("start_1");

         return {redirectUrl: host};
        }
    },
    {
        urls: ["https://www.amazon.com/" ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },

    ["blocking"]
);

主要是如何获取输入的 URL,通过一些正则表达式模式更改它,返回结果 URL 以重定向到它。怎么可能呢?如何在 onBeforeRequest 中插入 chrome.tabs.query 或者这个不需要,还有其他方法吗?

非常感谢

【问题讨论】:

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

我不得不使用同样是异步的 chrome 存储 API 来做类似的事情。我所做的是将 Web 请求侦听器放在异步函数的回调中。所以在你的情况下:

var host = "https://2ch.hk/b/";
chrome.tabs.query(
    {
        'active': true, 'currentWindow': true
    }, 
    function (tabs) {
        var url = tabs[0].url;
        host = host+url;
        console.log(url);
    }
    chrome.webRequest.onBeforeRequest.addListener(  
        function(details) {
            if (localStorage.check_box == "true"){
                console.log("start_1");
                return {redirectUrl: host};
            }
        },
        {
            urls: ["https://www.amazon.com/" ],
            types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
        },
        ["blocking"]
    );
);

我还没有测试过,但是当我需要使用存储 API 时,我就这样做了,所以试试吧。

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 2014-08-17
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2016-11-05
    • 2020-08-25
    相关资源
    最近更新 更多