URL forwarding using Chrome webRequest after response is received

随声附和 提交于 2019-11-30 16:22:15

web request API Methods

So, idea is to store the secondary URL from onHeadersReceived Event and fire a chrome.tabs.reload() event which fires onBeforeRequest event again which helps in redirecting.

Sample Demonstration

The following untested :) demonstration blocks all Facebook URL's and redirects them to Google upon receiving secondary URL, you can customize it further.

References

manifest.json

Ensure all permissions are available and register background page with extension.

{
  "name": "Hanlder for Navigation",
  "description": "http://stackoverflow.com/questions/16928912/url-forwarding-using-chrome-webrequest-after-response-is-received",
  "version": "1",
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"]
  },
  "permissions":["https://www.facebook.com/*","webRequest","webRequestBlocking","tabs"]
}

background.js

This code blocks all URL request to Facebook and redirects them to Google.

var _redirectURL = "";
// Register an event listener which 
//traces all requests before being fired
chrome.webRequest.onBeforeRequest.addListener(function (details) {
    if (_redirectURL != "") {
        return {
            redirectUrl: "http://www.google.co.in/" /*Redirection URL*/
        };
    }
}, {
    urls: ["*://www.facebook.com/*"] /* List of URL's */ * *
}, ["blocking"]); // Block intercepted requests until this handler has finished
chrome.webRequest.onHeadersReceived.addListener(function (details) {
    if (_redirectURL == "") {
        var secondaryURL = extractSecondaryURL(details);
        _redirectUrl = secondaryURL;
        chrome.tabs.reload();
    }
}, {
    urls: ["http://*/*", "https://*/*"]
}, ["blocking", "responseHeaders"]);

Output

All request(s) to Facebook are redirected to Google.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!