Google chrome extension 防止扩展基于URL列表和通知运行的最佳方法是什么?

Google chrome extension 防止扩展基于URL列表和通知运行的最佳方法是什么?,google-chrome-extension,Google Chrome Extension,我知道如何在清单中包含类似的内容: "exclude_matches" : ["*://somesite.somewhere.com/*"], 但是,这对于许多URL似乎并不有用 是否有方法检查外部文件以查看URL或模式是否存在 我是否可以在URL或模式存在时显示通知以提醒用户扩展名不可用?您不能将“排除匹配项”属性绑定到外部文件 如果您需要检查包含URL或模式的文件,我建议使用: 在你的背景页面(或者更好的事件页面)注册一个合适的监听器,例如。 当标签的位置被更新时,让你的背景或事件页面检

我知道如何在清单中包含类似的内容:

"exclude_matches" : ["*://somesite.somewhere.com/*"],
但是,这对于许多URL似乎并不有用

是否有方法检查外部文件以查看URL或模式是否存在

我是否可以在URL或模式存在时显示通知以提醒用户扩展名不可用?

您不能将“排除匹配项”属性绑定到外部文件

如果您需要检查包含URL或模式的文件,我建议使用

  • 在你的背景页面(或者更好的事件页面)注册一个合适的监听器,例如。

  • 当标签的位置被更新时,让你的背景或事件页面检查一个包含URL/模式的捆绑js文件,并决定是否应该注入内容脚本

  • 最后,使用将脚本注入网页(如果需要)

  • 根据请求,提供一些未经测试的代码以帮助您入门:

    在manifest.json中:

    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js",
            "lotsOfURLsAndOrPatterns.js"
        ]
    },
    ...
    
    ...
    // E.g.:
    var excludedURLsArray = [
        "<1st url...>",
        "<2nd url...>",
        ...
    ];
    ...
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.url) {
            // The URL has changed - you can device other methods for checking
            // if you need to inject the tab, according to your particular setup
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (info.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + info.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tabId, {
                "file": "myContentScript.js",
                "allFrames": false   // <-- or whatever suits you
            }
        }
    };
    
    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js"
        ]
    },
    ...
    
    // Do stuff...
    alert("I've been injected !\nHow cool is that !");
    
    var ajaxURL = "http://url.to.your/server";
    
    // Asynchronously fetch the list of excluded URLs
    // (use synchronous calls if it better suits your purpose)
    function getExcludedURLs(successCallback, failureCallback) {
        var ajaxRequest = new XMLHttpRequest();
        ajaxRequest.addEventListener("readystatechange", function() {
            if (ajaxRequest.readyState == 4) {   // <-- the request has completed
                if (ajaxRequest.status == 200) {
                    successCallback(ajaxRequest.responseText);
                } else {
                    failureCallback(ajaxRequest.statusText);
                }
            }
        });
        // Send an HTTP GET request and get the response asynchronously
        ajaxRequest.open("GET", url, true);
        ajaxRequest.send(null);
    }
    
    // A function to be called on AJAX request failure:
    //   alerts the user regarding the failure
    function onAJAXFailure(statusText) {
        alert("Unable to fetch the excluded URLs list :(\n"
              + "Error: " + statusText);
    }
    
    // Retuns a function to be called on AJAX request success:
    //   test if the URL is in the list and injects the content script
    // If you feel like delving into some more advanced concepts, 
    // look for "Closures in JS", e.g.: 
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
    function onAJAXSuccess(tab) {
        return function(responseText) {
            var excludedURLsArray = JSON.parse(responseText);
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (tab.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + tab.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tab.id, {
                "file": "content_script.js",
                "allFrames": false   // <-- or whatever suits you
            });
        };
    }
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.status && (info.status == "complete")) {
            getExcludedURLs(onAJAXSuccess(tab), onAJAXFailure);
        }
    });
    
    <?php
    $excludedURLs = array(
        "http://stackoverflow.com/",
        "http://www.stackoverflow.com/",
        "http://stackoverflow.com/questions/tagged/google-chrome-extension",
        "http://www.stackoverflow.com/questions/tagged/google-chrome-extension"
    );
    
    echo(json_encode($excludedURLs));
    exit();
    ?>
    
    。。。
    // 1. 请求权限以侦听选项卡中的更改
    // 2. 请求允许“干扰”任何网页
    //(使用“http”或“https”方案-针对其他方案进行适当修改)
    “权限”:{
    ...
    “标签”,
    “http://*/*”,
    “https://*/*”
    },
    ...
    //包括包含要检查的URL和/或模式的文件
    //在您的背景或事件页面中。
    “背景”:{
    
    “持久性”:错误,//新解决方案,考虑到OP的以下要求:

  • 用户无法修改的URL列表
  • 可以集中更新并立即生效的URL列表
  • 由于无法将“排除匹配”属性绑定到外部文件,因此可以通过AJAX和实现所需:

  • 使用

  • 当标签的位置被更新时,让您的背景或事件页面通过AJAX请求获取URL列表到您的服务器,并决定是否应该注入内容脚本。(根据您的具体要求,您可以让您的背景页面定期获取更新的文件,而不是在每次选项卡更新时要求更新,以获得更好的性能。)

  • 最后,使用将脚本注入网页(如果需要)

  • 看看来开始使用AJAX

    最后,还有一些演示和工作代码:

    在manifest.json中:

    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js",
            "lotsOfURLsAndOrPatterns.js"
        ]
    },
    ...
    
    ...
    // E.g.:
    var excludedURLsArray = [
        "<1st url...>",
        "<2nd url...>",
        ...
    ];
    ...
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.url) {
            // The URL has changed - you can device other methods for checking
            // if you need to inject the tab, according to your particular setup
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (info.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + info.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tabId, {
                "file": "myContentScript.js",
                "allFrames": false   // <-- or whatever suits you
            }
        }
    };
    
    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js"
        ]
    },
    ...
    
    // Do stuff...
    alert("I've been injected !\nHow cool is that !");
    
    var ajaxURL = "http://url.to.your/server";
    
    // Asynchronously fetch the list of excluded URLs
    // (use synchronous calls if it better suits your purpose)
    function getExcludedURLs(successCallback, failureCallback) {
        var ajaxRequest = new XMLHttpRequest();
        ajaxRequest.addEventListener("readystatechange", function() {
            if (ajaxRequest.readyState == 4) {   // <-- the request has completed
                if (ajaxRequest.status == 200) {
                    successCallback(ajaxRequest.responseText);
                } else {
                    failureCallback(ajaxRequest.statusText);
                }
            }
        });
        // Send an HTTP GET request and get the response asynchronously
        ajaxRequest.open("GET", url, true);
        ajaxRequest.send(null);
    }
    
    // A function to be called on AJAX request failure:
    //   alerts the user regarding the failure
    function onAJAXFailure(statusText) {
        alert("Unable to fetch the excluded URLs list :(\n"
              + "Error: " + statusText);
    }
    
    // Retuns a function to be called on AJAX request success:
    //   test if the URL is in the list and injects the content script
    // If you feel like delving into some more advanced concepts, 
    // look for "Closures in JS", e.g.: 
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
    function onAJAXSuccess(tab) {
        return function(responseText) {
            var excludedURLsArray = JSON.parse(responseText);
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (tab.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + tab.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tab.id, {
                "file": "content_script.js",
                "allFrames": false   // <-- or whatever suits you
            });
        };
    }
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.status && (info.status == "complete")) {
            getExcludedURLs(onAJAXSuccess(tab), onAJAXFailure);
        }
    });
    
    <?php
    $excludedURLs = array(
        "http://stackoverflow.com/",
        "http://www.stackoverflow.com/",
        "http://stackoverflow.com/questions/tagged/google-chrome-extension",
        "http://www.stackoverflow.com/questions/tagged/google-chrome-extension"
    );
    
    echo(json_encode($excludedURLs));
    exit();
    ?>
    
    background.js中

    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js",
            "lotsOfURLsAndOrPatterns.js"
        ]
    },
    ...
    
    ...
    // E.g.:
    var excludedURLsArray = [
        "<1st url...>",
        "<2nd url...>",
        ...
    ];
    ...
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.url) {
            // The URL has changed - you can device other methods for checking
            // if you need to inject the tab, according to your particular setup
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (info.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + info.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tabId, {
                "file": "myContentScript.js",
                "allFrames": false   // <-- or whatever suits you
            }
        }
    };
    
    ...
    // 1. Ask permission to listen for changes in tabs
    // 2. Ask permission to "interfere" with any web-page 
    // (using the "http" or "https" schemes - modify appropriately for other schemes)
    "permissions": {
        ...
        "tabs",
        "http://*/*", 
        "https://*/*"
    },
    ...
    // Include the file with the URLs and/or patterns to check
    // in your background- or event-page.
    "background": {
        "persistent": false,   // <-- Recommended, but optional
        "scripts": [
            "background.js"
        ]
    },
    ...
    
    // Do stuff...
    alert("I've been injected !\nHow cool is that !");
    
    var ajaxURL = "http://url.to.your/server";
    
    // Asynchronously fetch the list of excluded URLs
    // (use synchronous calls if it better suits your purpose)
    function getExcludedURLs(successCallback, failureCallback) {
        var ajaxRequest = new XMLHttpRequest();
        ajaxRequest.addEventListener("readystatechange", function() {
            if (ajaxRequest.readyState == 4) {   // <-- the request has completed
                if (ajaxRequest.status == 200) {
                    successCallback(ajaxRequest.responseText);
                } else {
                    failureCallback(ajaxRequest.statusText);
                }
            }
        });
        // Send an HTTP GET request and get the response asynchronously
        ajaxRequest.open("GET", url, true);
        ajaxRequest.send(null);
    }
    
    // A function to be called on AJAX request failure:
    //   alerts the user regarding the failure
    function onAJAXFailure(statusText) {
        alert("Unable to fetch the excluded URLs list :(\n"
              + "Error: " + statusText);
    }
    
    // Retuns a function to be called on AJAX request success:
    //   test if the URL is in the list and injects the content script
    // If you feel like delving into some more advanced concepts, 
    // look for "Closures in JS", e.g.: 
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
    function onAJAXSuccess(tab) {
        return function(responseText) {
            var excludedURLsArray = JSON.parse(responseText);
            for (var i = 0; i < excludedURLsArray.length; i++) {
                // Look for an exact match with an excluded URL
                // (modify according to your needs - e.g. check host only, etc)
                if (tab.url == excludedURLsArray[i]) {
                    // No injection - inform user and return
                    alert("Extension not available on '" + tab.url + "'.\n"
                          + "You are on your own !");
                    return;
                }
            }
    
            // Ending up here means we must inject...
            chrome.tabs.executeScript(tab.id, {
                "file": "content_script.js",
                "allFrames": false   // <-- or whatever suits you
            });
        };
    }
    
    // Add a listener for the "onUpdated" event
    chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
        if (info.status && (info.status == "complete")) {
            getExcludedURLs(onAJAXSuccess(tab), onAJAXFailure);
        }
    });
    
    <?php
    $excludedURLs = array(
        "http://stackoverflow.com/",
        "http://www.stackoverflow.com/",
        "http://stackoverflow.com/questions/tagged/google-chrome-extension",
        "http://www.stackoverflow.com/questions/tagged/google-chrome-extension"
    );
    
    echo(json_encode($excludedURLs));
    exit();
    ?>
    
    var ajaxURL=”http://url.to.your/server";
    //异步获取已排除URL的列表
    //(如果更适合您的目的,请使用同步调用)
    函数getExcludedURLs(successCallback,failureCallback){
    var ajaxRequest=new-XMLHttpRequest();
    addEventListener(“readystatechange”,function()){
    
    if(ajaxRequest.readyState==4){/@user1452893:添加了一些未经测试的示例代码。如果您在实现它时有任何问题或面临任何问题,请随时回来。此外,请不要忘记将答案标记为已接受,如果它有助于您解决问题;)非常感谢您为此付出了额外的努力!这是一个很大的帮助。将于今晚开始工作。我无法使lotsOfURLsAndOrPatterns.js驻留在外部位置,因此,如果每次添加或删除url时都需要更新CRX,则它将不起作用(@user1452893:抱歉,我没有意识到这是一个要求。我可以提出两个解决方案:1.使用chrome.storage或localStorage存储URL列表,并实现一个页面(在您的扩展中)来修改它们。2.如果是个人使用,您可以使用任何编辑器编辑lotsOfURLsOrPatterns.js。例如,在Windows中:“\AppData\Local\Google\Chrome\User Data\Default\\\lotsOfURLsOrPatterns.js”(由于这是一条很长的路径,您可以创建一个指向它的快捷方式,然后双击进行编辑。)@ExpertSystems感谢您的注释。1)将向用户公开并可能将“黑名单”的控制权交给用户,而这是不可行的。2)非个人使用。我对localStorage和Chrome的版本有一定的经验,但在每次修订时避免CRX更新的同时,我看不到适用的路径。一如既往地感谢您的帮助。我唯一能想到的可能是对外部JSON文件进行AJAX调用,以检查但高于我的工资等级的代码。@ExpertSystems no joy.TAJAX似乎不起作用。例如,当php fie不可用时不会抛出错误。不会发出“你自己来!”警报(可能是同一原因)。最后,content.js警报会多次发出(有时40+)。不确定我做错了什么。我不知道该说什么。我在发布之前对它进行了mtself测试,它对我来说很好。但它并不意味着可以作为生产准备解决方案,jyst只是一个粗略的草稿来帮助您开始。您可能希望对它进行增强,例如捕获和处理更多事件。它绝对不应该为每个选项卡upd触发超过一次ate,但(一如既往)您必须找出(在您的特定设置中)导致问题的原因,以便修复它:)@ExpertSystems感谢您的提醒。我确实认为问题在于AJAX调用没有启动。我们如何作为第一步检查它。php文件返回并返回数据。但是,如果我将其从服务器中删除,我甚至不会收到您的错误消息。我怀疑如果AJAX调用不成功,任何事情都不会起作用。@user1452893:我真的不知道知道为什么它不适合你。我使用一个不存在的目标URL测试它,并且正常执行
    failureCallback
    (当然没有响应,因为URL不存在)。我怀疑你没有使用我上面给出的确切代码,所以我无法帮助调试一些我看不到的代码。请发布一篇演示问题的文章(即,调用不存在的URL和failureCallbac未被激发)。@Expert