【问题标题】:How to create an exception for <all_urls> in Chrome extension?如何在 Chrome 扩展中为 <all_urls> 创建一个例外?
【发布时间】:2017-03-15 15:38:43
【问题描述】:

我已阅读 Match all URLs except certain URLs in Chrome Extension,但其接受的解决方案仅适用于清单文件中的内容脚本。

background.js

我有以下工作代码:

chrome.webRequest.onBeforeSendHeaders.addListener(handler, {urls: ["<all_urls>"] },  ["blocking", "requestHeaders"]);

出现问题是因为我需要它应用于除一个以外的所有网址*://*.facebook.com/*)。

如何创建这个异常?

如果唯一的解决方案是正则表达式,请指导我如何正确编写它?

【问题讨论】:

    标签: regex google-chrome-extension regex-negation


    【解决方案1】:

    在为webRequest 事件调用addListener 时可以提供的过滤器,即RequestFilter type,使用match patterns (where the docs say this)。匹配模式无法满足您的要求:排除特定 URL,而允许所有其他 URL。

    您必须通过检查传递给您的侦听器的details Objecturl 属性在您的webRequest handler 中执行排除。这样做可能是这样的:

    function listenForWebrequest(details){
        if(/^[^:]*:(?:\/\/)?(?:[^\/]*\.)?facebook.com\/.*$/.test(details.url)) {
            //The URL matched our exclusion criteria
            return;
        } //else
        //Do your normal event processing here
    }
    
    chrome.webRequest.onBeforeSendHeaders.addListener(listenForWebrequest, {
        urls: ["<all_urls>"] 
    },  ["blocking", "requestHeaders"]);
    

    【讨论】:

    • 不应该^[^:]*:(?:\/\/)?(?:[^\.]*\.)?facebook.com\/.*$更精确吗?
    • @quackkkk,这取决于您要匹配的内容。 (?:[^\/]*\.)? 将匹配任意数量的子或子子(等)域(例如 bar.foo.games.facebook.com)。 (?:[^\.]*\.)? 将仅匹配一个子域(例如 www.facebook.comimages.facebook.com,但不匹配 foo.games.facebook.com)。您使用什么将取决于您实际需要什么。我假设您想排除(即匹配)facebook.com 中的任何内容(即 Facebook 控制的任何内容)。
    • 酷,我没有考虑子子域的可能性 - 再次感谢@Makyen的解释!
    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2021-05-19
    • 2013-09-18
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多