重定向到新的URL使用onBeforeRequest和Chrome .tab .query (Chrome扩展)

Redirect to new URL using onBeforeRequest and chrome.tabs.query (Chrome Extension)

本文关键字:Chrome tab query 扩展 onBeforeRequest URL 使用 重定向      更新时间:2023-09-26

祝你好运。

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

我的manifest文件:

 {
  "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以重定向到它。怎么可能做到呢?如何插入chrome.tabs。查询内部onBeforeRequest或这不需要,有另一种方式?

大谢谢

我不得不使用chrome存储API做类似的事情,这也是异步的。我所做的是把web请求监听器放在async函数的回调中。所以在你的例子中:

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时所做的,所以请尝试一下。