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

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

问题描述

如果扩展程序拦截任何请求的URL,以便在某些条件匹配的情况下拦截它,那么如何才能阻止它?

Firefox的类似问题



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

解决方案

JavaScript代码:



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

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

以下示例以更高效的方式实现了相同的目标,因为请求不是针对www。 evil.com不需要传递给扩展名:

  chrome.webRequest.onBeforeRequest.addListener(
function (详情){
return {cancel:true};
},
{url:[*://www.evil.com/*]},
[ 阻塞]
);

注册事件侦听器

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



Web请求API的addListener )有以下定义:

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

以下是监听onBeforeRequest事件的示例:

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

manifest.json需要的权限

 权限:[
webRequest,
webRequestBlocking,
标签,
< all_urls> 中
],

扩展程序示例和帮助链接 p>


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?

解决方案

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:

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

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