在firefox扩展中我想拦截url浏览器正在发出请求并在某些条件匹配时完全阻止请求
如何拦截被请求的网址
答案 0 :(得分:5)
您可以查看这些插件的来源
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
进行快速处理
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');
}
}
};
要开始观察所有请求,请执行此操作(例如,在启动插件时)
for (var o in observers) {
observers[o].reg();
}
重要的是要停止观察(确保至少在关闭插件时运行它,你不想让观察者因记忆原因而注册)
for (var o in observers) {
observers[o].unreg();
}
阻止/重定向网址的观察员服务的完整工作示例:https://github.com/Noitidart/PortableTester/tree/block-urls
答案 1 :(得分:3)
另一种可能的解决方案:
以下是HTTPS-Everywhere
中的模块示例的其他实现初始化功能:
init: function() {
// start observing all http requests
Services.obs.addObserver(httpNowhere, "http-on-modify-request", false);
},
观察员功能:
observe: function(subject, topic, data) {
var request = subject.QueryInterface(Ci.nsIHttpChannel);
if (topic == "http-on-modify-request") {
if (request.URI.spec == "xxx.example.com") {
request.redirectTo("yyy.example.com");
}
else {
request.cancel(Components.results.NS_ERROR_ABORT);
}
}
},
示例插件:
HTTPS-Nowhere - https://github.com/cwilper/http-nowhere
HTTPS-Everywhere - https://github.com/EFForg/https-everywhere
将您的扩展程序迁移到chrome:
我在此页面中回答了您关于chrome的问题: Chrome Extension : How to intercept requested urls?