use*_*308 2 javascript firefox firefox-addon firefox-addon-sdk
在firefox扩展中我想截取url浏览器正在发出请求并在某些条件匹配时完全阻止请求
我该如何拦截被请求的URL
你可以看一下这些插件的来源
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 =搜索
或使用服务观察员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');
}
}
};
Run Code Online (Sandbox Code Playgroud)
要开始观察所有请求,请执行此操作(例如,在启动插件时)
for (var o in observers) {
observers[o].reg();
}
Run Code Online (Sandbox Code Playgroud)
停止观察是很重要的(确保至少在关闭插件时运行它,你不想因为内存原因而让观察者注册)
for (var o in observers) {
observers[o].unreg();
}
Run Code Online (Sandbox Code Playgroud)
阻止/重定向URL的观察者服务的完整工作示例:https://github.com/Noitidart/PortableTester/tree/block-urls
| 归档时间: |
|
| 查看次数: |
2841 次 |
| 最近记录: |