Chrome扩展程序:如何拦截请求的网址? [英] Chrome extension: how to intercept requested urls?

查看:622
本文介绍了Chrome扩展程序:如何拦截请求的网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某些条件匹配,扩展程序如何拦截任何请求的URL来阻止它? (针对Firefox的类似问题

How can an extension intercept any requested URL to block it if some condition matches? (similar question for Firefox)

需要在manifest.json中设置什么权限?

What permission needs to be set in manifest.json?

推荐答案

JavaScript代码:

JavaScript Code :

以下示例说明了如何阻止对www.evil.com的所有请求:

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"]
);

下面的示例以更有效的方式实现了相同的目标,因为未定向到www的请求。 evil.com不需要传递给扩展名:

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"]
);

注册事件监听器:

要为Web请求注册事件侦听器,请对通常的 addListener()函数使用一个变体。除了指定回调函数外,还必须指定过滤器参数,还可以指定可选的额外信息参数。

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.

Web请求API的三个参数addListener( )具有以下定义:

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

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

下面是一个监听onBeforeRequest事件的示例:

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

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

manifest.json所需的权限:

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

扩展示例和帮助链接:

  • 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

这篇关于Chrome扩展程序:如何拦截请求的网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆