2

I am trying to test this code here. This code "blocks" some URL if I try to join them.

//const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var urls_block = [ 
    //If URLs contain any of these elements they will be blocked or redirected,
    //  your choice based on code in observer line 17
    'www.facebook.com'
];
var redir_obj = {
    'www.facebook.com': 'data:text,'+ escape('url_blocked would have went to facebook')
}
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.toLowerCase();
            for (var i=0; i<urls_block.length; i++) {
                if (requestUrl.indexOf(urls_block[i]) > -1) {
                    //httpChannel.cancel(Cr.NS_BINDING_ABORTED); //this aborts the load
                    //Can redirect with this next line, if don't want to redirect and
                    //  just block, then comment this line and uncomment the line above:
                    httpChannel.redirectTo(Services.io.newURI(redir_obj[urls_block[i]],
                                               null, null));
                    break;
                }
            }
        },
        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');
        }
    }
};
function install() {}
function uninstall() {}
function startup() {
    for (var o in observers) {
        observers[o].reg();
    }
}

function shutdown(aData, aReason) {
    if (aReason == APP_SHUTDOWN) return;

    for (var o in observers) {
        observers[o].unreg();
    }
}

startup()

In scratchpad of Firefox and I get this error:

/*
Exception: ReferenceError: Cu is not defined
@Scratchpad/1:2:1
*/

NO ERROR ON CONSOLE.

Does anyone have any idea what is this error??
I've read that Firefox doesn't go well with constants but this code sometimes works sometimes not.

Also can someone help me fixing it, so it can work all the time?

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • As to it sometimes working, or sometimes not, we are going to need more information from you as to how it is not working (e.g. what shows up in the console when it works/doesn't work)? With the information you have provided, it is easy to see why you get the reported error, but it would just be a guess as to what you are seeing otherwise. Unfortunately, given that you had the "Cu is not defined" error in your question, anything further should be a new question. Questions should be focused as much as possible on one specific problem. See [ask]. – Makyen Jun 25 '15 at 09:11
  • @Mayken it might have worked for him on the first time if the scope the scratchpad was running it didnt have Cu defined as const. so a second run would be error – Noitidart Jun 25 '15 at 10:59

3 Answers3

1

There are multiple problems. First, in order for Components to be defined, you need to have the scratchpad running in the browser context. To do this go to the Developer Tool Settings and check the box that is "Enable chrome and add-on debugging". Restart Firefox, just to be sure that the scratchpad is in the browser context.

Once that is done, the following code will work:

// -sp-context: browser
//The above line tells scratchpad to run this in the browser context.
//In the scratchpad browser context some of these are already defined, so we check first:
if(typeof Cc === "undefined") {
    const Cc = Components.classes;
}
if(typeof Ci === "undefined") {
    const Ci = Components.interfaces;
}
if(typeof Cu === "undefined") {
    const Cu = Components.utils;
}
if(typeof Cr === "undefined") {
    const Cr = Components.results;
}
//In your own add-on you will need to define them all:
//const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var urlsBlock = [ 
    //If URLs contain any of these elements they will be blocked or redirected,
    //  your choice based on code in observer line 17
    'www.facebook.com'
];
var redirObj = {
    'www.facebook.com': 'data:text,'+ escape('url_blocked would have went to facebook')
}
var observers = {
    'http-on-modify-request': {
        observe: function (aSubject, aTopic, aData) {
            var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
            var requestUrl = httpChannel.URI.spec.toLowerCase();
            console.info('http-on-modify-request: aSubject = ' 
                          + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData
                          + ' | httpChannel = ' + httpChannel 
                          + ' | requestUrl = ' + requestUrl);
            for (let urlsBlockLength=urlsBlock.length, i=0; i<urlsBlockLength; i++) {
                if (requestUrl.indexOf(urlsBlock[i]) > -1) {
                    //httpChannel.cancel(Cr.NS_BINDING_ABORTED); //this aborts the load
                    //Can redirect with this next line, if don't want to redirect and
                    //  just block, then comment this line and uncomment the line above:
                    httpChannel.redirectTo(Services.io.newURI(redirObj[urlsBlock[i]],
                                               null, null));
                    break;
                }
            }
        },
        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');
        }
    }
};
function install() {}
function uninstall() {}
function startup() {
    for (var o in observers) {
        observers[o].reg();
    }
}

function shutdown(aData, aReason) {
    if (aReason == APP_SHUTDOWN) return;

    for (var o in observers) {
        observers[o].unreg();
    }
}

startup();
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • Nope its not working either when i uncomment the first line. When its working, it doesnt show any error on the code and when i try to join facebook.com it says `url_blocked that would have went to facebook` as it supposed to do. But when its not working, it shows the error that i said on the post. Also no error on the browser console. –  Jun 25 '15 at 09:09
  • @SteliosM. Are you saying that you still get the reported error "Cu is not defined" when the first line of the code is not commented-out? You are going to need to be more clear as to what you mean by working or not working, and how you are testing it. – Makyen Jun 25 '15 at 09:42
  • Yes, when i comment-out the first line i still get the error in scratchpad. and when i try to join facebook.com it goes to the page. So my code does not work cause its programmed to block facebook.com and replace it with the text in line 9 `'url_blocked would have went to facebook'` –  Jun 25 '15 at 09:44
  • If you're running this from scratchpad you have to uncomment that line. When you eventually deploy it in your addon, that line is absolutely required. – Noitidart Jun 25 '15 at 10:13
  • @SteliosM. There were multiple other problems. I have added updated, tested, code to the answer. – Makyen Jun 25 '15 at 10:30
1

I had this problem, It is so easy, it is enough to change your environment of scratchpad from Content to Browser

Hosein Aqajani
  • 1,553
  • 4
  • 26
  • 46
0

The code works as is except for shutdown but thats obvious because its from scratchpad scope. This code is designed ot run form bootstrap scope. But to make it run form scratchpad you comment out first line and just run startup. then to shutdown just run the loop from within shutdown as APP_SHUTDOWN is not defined. <<< for scrathcpad scope, which is for testing purposes only. Once you want to deploy it use the uncommented line 1 code and no need to run startup or shutodwn as they are bootstrap entry and exit functions so they automatically get called. See the youtube video:

https://www.youtube.com/watch?v=pxt8lJ64nVw

Noitidart
  • 35,443
  • 37
  • 154
  • 323