Chrome Extension: How to redirect to a custom HTML page in response to specific web request?

前端 未结 2 793
眼角桃花
眼角桃花 2021-02-10 05:53

I\'d like to write an extension that redirects all web traffic to a specific domain, let\'s say wikipedia.org, to an intermediate page that says something like, \"Whoa,

2条回答
  •  没有蜡笔的小新
    2021-02-10 06:12

    You can do this using webRequest feature, a background page, and custom page with yes and no buttons. For example, write something similar in the background page:

    var URLStorage;
    
    function interceptRequest(request)
    {
      if(request && request.url)
      {
        if(request.type == "main_frame") // new page/site is loading in main window
        {
          if(request.url.indexOf("wikipedia.org") > -1)
          {
            URLStorage = request.url;
            return {redirectUrl: chrome.extension.getURL("confirmation.html")};
          }
        }
      }
    }
    
    chrome.webRequest.onBeforeRequest.addListener(interceptRequest, {urls: ["*://*/*"]}, ['blocking']);
    

    This example does not strictly check if wikipedia is mentioned in domain, but I did this for clarity. In my real code a special class 'URL' is used which parses passed url and provides properties for every part of it, so they can be checked selectively.

    In the confirmation.html just place 2 buttons, and bind them to an appropriate code, for example redirecting to requested site, if a user answered "yes".

    $('#okbutton').click(function()
    {
      document.location.href = chrome.extension.getBackgroundPage().URLStorage;
    });
    

    Don't forget to mention "webRequest" and "webRequestBlocking" in permissions section of your manifest.

提交回复
热议问题