Firefox扩展:如何有条件地拦截请求的URL并将其阻止? [英] Firefox extension: How to intercept the requested url conditionally and block it?
问题描述
在我的Firefox扩展程序中,我想拦截浏览器正在请求的网址,并在某些条件匹配时完全阻止该请求
In my Firefox extension I want to intercept the url that the browser is requesting and block the request entirely if some condition matches
如何截获所请求的URL?
How can I intercept URL being requested?
推荐答案
您可以查看这些插件的来源
you can have a look at the source of those addons
https://addons.mozilla.org/en-us/firefox/addon/blocksite/?src = search https://addons.mozilla.org/en -us/firefox/addon/url-n-extension-blockune-bl/?src = search
或将服务观察器与nsIHTTPChannel
一起使用以进行快速处理
or use service observer with nsIHTTPChannel
for fast handling
const { Ci, Cu, Cc, Cr } = require('chrome'); //const {interfaces: Ci, utils: Cu, classes: Cc, results: Cr } = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var observers = {
'http-on-modify-request': {
observe: function (aSubject, aTopic, aData) {
console.info('http-on-modify-request: aSubject = ' + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData);
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
var requestUrl = httpChannel.URI.spec
if (requestUrl.indexOf('google.com') > -1) {
//httpChannel.cancel(Cr.NS_BINDING_ABORTED); //this aborts the load
httpChannel.redirectTo(Services.io.newURI('data:text,url_blocked', null, null)); //can redirect with this line, if dont want to redirect and just block, then uncomment this line and comment out line above (line 17)
}
},
reg: function () {
Services.obs.addObserver(observers['http-on-modify-request'], 'http-on-modify-request', false);
},
unreg: function () {
Services.obs.removeObserver(observers['http-on-modify-request'], 'http-on-modify-request');
}
}
};
开始观察
要开始观察所有请求,请执行此操作(例如,在启动插件时)
To start observing
To start start obseving all requests do this (for example on startup of your addon)
for (var o in observers) {
observers[o].reg();
}
停止观察
停止观察很重要(确保至少在插件关闭时运行此命令,出于内存原因,您不想让观察者注册)
To stop observing
Its important to stop observring (make sure to run this at least on shutdown of addon, you dont want to leave the observer registered for memory reasons)
for (var o in observers) {
observers[o].unreg();
}
观察者服务的完整工作示例,用于阻止/重定向URL: https://github.com/Noitidart/PortableTester/tree/block-urls
Full working example of the observer service to block/redirect urls: https://github.com/Noitidart/PortableTester/tree/block-urls
这篇关于Firefox扩展:如何有条件地拦截请求的URL并将其阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!