Firefox 扩展:如何有条件地拦截请求的 url 并阻止它?

Firefox extension: How to intercept the requested url conditionally and block it?

在我的 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=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();
}

block/redirect url 的观察者服务的完整工作示例:https://github.com/Noitidart/PortableTester/tree/block-urls

另一个可能的解决方案:

这是来自 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-无处 - https://github.com/cwilper/http-nowhere

无处不在的 HTTPS - https://github.com/EFForg/https-everywhere

正在将您的扩展程序迁移到 chrome:

我在本页中回答了 chrome 的问题: