Chrome Extension : How to intercept requested urls? [closed]

社会主义新天地 提交于 2019-12-17 22:51:33

问题


How can an extension intercept any requested URL to block it if some condition matches?

Similar question for Firefox.

What permission needs to be set in manifest.json?


回答1:


JavaScript Code :

The following example illustrates how to block all requests to www.evil.com:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return {cancel: details.url.indexOf("://www.evil.com/") != -1};
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

The following example achieves the same goal in a more efficient way because requests that are not targeted to www.evil.com do not need to be passed to the extension:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) { 
    return { cancel: true }; 
  },
  {urls: ["*://www.evil.com/*"]},
  ["blocking"]
);

Registering event listeners:

To register an event listener for a web request, you use a variation on the usual addListener() function. In addition to specifying a callback function, you have to specify a filter argument and you may specify an optional extra info argument.

The three arguments to the web request API's addListener() have the following definitions:

var callback = function(details) {...};
var filter = {...};
var opt_extraInfoSpec = [...];

Here's an example of listening for the onBeforeRequest event:

chrome.webRequest.onBeforeRequest.addListener(
  callback, filter, opt_extraInfoSpec);

Permission needed on manifest.json :

"permissions": [
  "webRequest",
  "webRequestBlocking",
"tabs",
"<all_urls>"
],

Extensions examples and help links:

  • Extension Requestly : https://chrome.google.com/webstore/detail/requestly/mdnleldcmiljblolnjhpnblkcekpdkpa
  • Extension Https-Everywhere : https://github.com/EFForg/https-everywhere
  • Example : https://github.com/blunderboy/requestly/blob/master/src/background/background.js
  • Wiki : https://code.google.com/p/html5security/wiki/RedirectionMethods
  • Wiki : https://developer.chrome.com/extensions/webRequest


来源:https://stackoverflow.com/questions/30590428/chrome-extension-how-to-intercept-requested-urls

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