阻止Chrome扩展程序中onBeforeNavigate事件指示的导航

时间:2016-09-05 15:08:52

标签: google-chrome google-chrome-extension

我想将浏览器限制在一组网址中。我正在使用:

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

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

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

2 个答案:

答案 0 :(得分:3)

以下扩展程序为loan_amount = float(input("Enter loan amount in dollars (exclude commas):")) length_years = int(input("Enter the amount of years as an integer:")) 添加了一个监听器,该监听器用于记住,由tabId索引,该事件被触发的webNavigation.onCompleted中的最新URL和先前的URL。

监听器已添加到frameId==0,用于监控匹配的网址,在本例中为webNavigation.onBeforeNavigate。如果网址匹配,则会通过stackexchange.com更新标签网址,以导航回触发tabs.update事件的最后一个网址。

如果webNavigation.onCompleted事件适用于除onBeforeNavigate以外的frameId,则该标签会导航到为{{0事件触发的上一个网址onCompleted 1}}。如果没有使用先前的URL,那么我们可以进入一个循环,其中重复地重新加载当前URL,因为其中一个框架中的URL与我们阻止的URL匹配。处理此问题的更好方法是注入内容脚本以更改框架的frameId==0属性。然后我们需要处理帧内的帧。

blockNavigation.js

src

的manifest.json

//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
        });

    });
});

答案 1 :(得分:2)

有可能完全阻止导航。使用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"]
  );