Chrome 扩展检查 link 并重定向到另一个网站

Chrome extension to check a link and redirect to another website

我正在构建一个扩展,我想在其中从我的 chrome/firefox 浏览器中阻止某些网站 url。

假设我有一个 URLS 列表,我想将其设为黑名单。 因此,每当 chrome 用户想要加入他们时,扩展程序将重定向到我选择的另一个 URL(在代码中我将确定我想要的 URL)

通过一些研究,我设法 CHROME 这个

manifest.json

{
    "name": "URL Block",
    "description": "Redirect to another site",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "permissions": [
        "webRequest",
                    "*://facebook.com/*",
            "*://www.facebook.com/*",
            "*://apple.com/*",
            "*://www.apple.com/*",
            "*://iptorrents.com/*",
            "*://www.iptorrents.com/*",
        "webRequestBlocking"
    ]
}

background.js

var host = "http://www.google.com";
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
         return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
    },
    {
        urls: [
            "*://facebook.com/*",
            "*://www.facebook.com/*",
            "*://apple.com/*",
            "*://www.apple.com/*",
            "*://iptorrents.com/*",
            "*://www.iptorrents.com/*"
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
    ["blocking"]
);

所以这个扩展非常适合我想要做的事情。 但是现在我有一些问题。

问题:

假设我希望扩展重定向到 2 个不同的 URL (而且不仅仅是在我上面的示例中的 google.com 中。) [这意味着,当我输入 URL: www.facebook.com 并按回车键时,扩展程序会将特定标签重定向到 www.google.com 并打开一个新标签以重定向到 www.abc.com]

我不知道如何在 chrome 中执行此操作,但使用 Firefox 时,您可以这样做:

How can I change the User Agent in just one tab of Firefox? in that solution instead of httpChannel.setRequestHeader do httpChannel.redirectTo you can read about redirectTo here: https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIHttpChannel#redirectTo%28%29

您可以同时重定向标签页 打开一个新标签页,这似乎是您想要实现的目标。

就这么简单(在 onBeforeRequest 侦听器中):

function(details) {
  chrome.tabs.create({
    url: "your 2nd URL",
    active: true // Change to false if you want it to open in the background
                 // and see the docs for more options
  });
  return {redirectUrl: "your 1st URL" };
}

但是,您可能不想在每次 访问 URL 时都打开一个新选项卡。请注意您的 types 声明:

types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]

这意味着每次 任何 页面尝试从这些站点加载资源时,您都会弹出一个新选项卡。所以,最好按类型筛选:

function(details) {
  if(details.type == "main_frame") {
    chrome.tabs.create({
      url: "your 2nd URL",
      active: true
    });
  }
  return {redirectUrl: "your 1st URL" };
}