阻止由Chrome扩展中的onBeforeNavigate事件指示的导航,但不是非导航请求



我想将浏览器限制在一组url内。我使用:

chrome.webNavigation.onBeforeNavigate.addListener(functon(details){
    if (notAllowed(details.url)) {
         // Do something to stop navigation
    }
});

我知道我可以消去chrome.webRequest.onBeforeRequest。但是,我不想阻止请求,如XHR或任何其他。我希望这个过滤器只用于导航。

对于用户来说,它应该看起来像,链接(例如<a href="http://...">foo</a>)点击事件被停止

以下扩展为webNavigation.onCompleted添加了一个侦听器,该侦听器用于记住由tabId索引的frameId==0中触发事件的最新URL和先前的URL。

一个监听器被添加到webNavigation.onBeforeNavigate,它监视匹配的url,在本例中是stackexchange.com。如果URL匹配,则通过tabs.update更新选项卡URL,以导航到触发webNavigation.onCompleted事件的最后一个URL。

如果onBeforeNavigate事件是针对frameId而不是0,则选项卡将导航到frameId==0触发onCompleted事件的前一个URL。如果之前的URL没有被使用,那么我们就会进入一个循环,在这个循环中,由于其中一个帧中的URL与我们正在阻止的URL匹配,当前URL会被反复重新加载。处理这个问题的更好方法是注入一个内容脚本来更改框架的src属性。然后我们需要处理帧中的帧。

blockNavigation.js :

//Remember tab URLs
var tabsInfo = {};
function completedLoadingUrlInTab(details) {
    //console.log('details:',details);
    //We have completed loading a URL.
    createTabRecordIfNeeded(details.tabId);
    if(details.frameId !== 0){
        //Only record inforamtion for the main frame
        return;
    }
    //Remember the newUrl so we can check against it the next time
    //  an event is fired.
    tabsInfo[details.tabId].priorCompleteUrl = tabsInfo[details.tabId].completeUrl;
    tabsInfo[details.tabId].completeUrl = details.url;
}
function InfoForTab(_url,_priorUrl) {
    this.completeUrl = (typeof _url !== 'string') ? "" : _url;
    this.priorCompleteUrl = (typeof _priorUrl !== 'string') ? "" : _priorUrl;
}
function createTabRecordIfNeeded(tabId) {
    if(!tabsInfo.hasOwnProperty(tabId) || typeof tabsInfo[tabId] !== 'object') {
        //This is the first time we have encountered this tab.
        //Create an object to hold the collected info for the tab.
        tabsInfo[tabId] = new InfoForTab();
    }
}

//Block URLs
function blockUrlIfMatch(details){
    createTabRecordIfNeeded(details.tabId);
    if(/^[^:/]+://[^/]*stackexchange.[^/.]+//.test(details.url)){
        //Block this URL by navigating to the already current URL
        console.log('Blocking URL:',details.url);
        console.log('Returning to URL:',tabsInfo[details.tabId].completeUrl);
        if(details.frameId !==0){
            //This navigation is in a subframe. We currently handle that  by
            //  navigating to the page prior to the current one.
            //  Probably should handle this by changing the src of the frame.
            //  This would require injecting a content script to change the src.
            //  Would also need to handle frames within frames. 
            //Must navigate to priorCmpleteUrl as we can not load the current one.
            tabsInfo[details.tabId].completeUrl = tabsInfo[details.tabId].priorCompleteUrl;
        }
        var urlToUse = tabsInfo[details.tabId].completeUrl;
        urlToUse = (typeof urlToUse === 'string') ? urlToUse : '';
        chrome.tabs.update(details.tabId,{url: urlToUse},function(tab){
            if(chrome.runtime.lastError){
                if(chrome.runtime.lastError.message.indexOf('No tab with id:') > -1){
                    //Chrome is probably loading a page in a tab which it is expecting to
                    //  swap out with a current tab.  Need to decide how to handle this
                    //  case.
                    //For now just output the error message
                    console.log('Error:',chrome.runtime.lastError.message)
                } else {
                    console.log('Error:',chrome.runtime.lastError.message)
                }
            }
        });
        //Notify the user URL was blocked.
        notifyOfBlockedUrl(details.url);
    }
}
function notifyOfBlockedUrl(url){
    //This will fail if you have not provided an icon.
    chrome.notifications.create({
        type: 'basic',
        iconUrl: 'blockedUrl.png',
        title:'Blocked URL',
        message:url
    });
}

//Startup
chrome.webNavigation.onCompleted.addListener(completedLoadingUrlInTab);
chrome.webNavigation.onBeforeNavigate.addListener(blockUrlIfMatch);
//Get the URLs for all current tabs when add-on is loaded.
//Block any currently matching URLs.  Does not check for URLs in frames.
chrome.tabs.query({},tabs => {
    tabs.forEach(tab => {
        createTabRecordIfNeeded(tab.id);
        tabsInfo[tab.id].completeUrl = tab.url;
        blockUrlIfMatch({
            tabId : tab.id,
            frameId : 1, //use 1. This will result in going to '' at this time.
            url : tab.url
        });
    });
});

manifest.json :

{
    "description": "Watch webNavigation events and block matching URLs",
    "manifest_version": 2,
    "name": "webNavigation based block navigation to matched URLs",
    "version": "0.1",
    "permissions": [
        "notifications",
        "webNavigation",
        "tabs"
    ],
    "background": {
        "scripts": ["blockNavigation.js"]
    }
}

完全可以阻止导航。使用redirectURL并设置一个生成204(无内容)响应的链接。

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    //just don't navigate at all if the requested url is example.com
    if (details.url.indexOf("://example.com/") != -1) {
      return {redirectUrl: 'http://google.com/gen_204'};
    } else {
      return { cancel: false };
    }
  },
    { urls: ["<all_urls>"] },
    ["blocking"]
  );

webRequest.onBeforeRequest有一个.type字段,可用于确定发出请求的原因。对于只加载页面的请求,检查details.type === "main_frame",并包括在iframe内导航的请求,也检查details.type === "sub_frame"

browser.webRequest.onBeforeRequest.addListener(
    (details) => {
        if (details.type !== "main_frame" || details.method !== "GET") {
            return;
        }
    },
    { urls: ["<all_urls>"] },
    ["blocking"],
);
        permissions: [
            "webRequest",
            "webRequestBlocking",
            "http://*/",
            "https://*/",
        ],

最新更新