user3833308 user3833308 - 1 year ago 107
Javascript Question

firefox extension: intercepting url it is requesting and blocking conditionally

in firefox extension I want to intercept the url browser is making request to and block the request entirely if some condition matches

how can I intercept URL being requested

Answer Source

you can have a look at the source of those addons

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;

var observers = {
    'http-on-modify-request': {
        observe: function (aSubject, aTopic, aData) {
  'http-on-modify-request: aSubject = ' + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData);
            var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
            var requestUrl = httpChannel.URI.spec
            if (requestUrl.indexOf('') > -1) {
               //httpChannel.cancel(Cr.NS_BINDING_ABORTED); //this aborts the load
               httpChannel.redirectTo('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) {

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) {

Full working example of the observer service to block/redirect urls:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download