Search code examples
javascriptfirefox-addonfirefox-addon-sdk

How to determine the http-request's location/origin (address-bar)?


So I'm trying to redirect the browser to another webpage when the page he is attempting to load matches my conditions (regex). Currently it looks like this: (came up with it here)

function listener(event) {
    var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
    var url = event.subject.URI.spec;

    if (isToBeRedirected(url)) {
        // replace url
    }
}

exports.main = function() {
    events.on("http-on-modify-request", listener);
}

But the problem is, that this will also replace urls to images for example, which are embedded in the page. My question would be, is there a way of varyfying that the http request is made by typing in a url or clicking a link to a page? So simply everytime a url shows up in the address-bar.
I thought about reading the url of the current tab and comparing it to the request url, but I wasnt able to find out exactly how yet.


Solution

  • I have an idea.

    If you do console.log(Ci.nsIHttpChannel) you see it has a bunch of flags, see img at bottom.

    So I'm thinking test if it's the main load, meaning its not in a sub frame, but its the whole document of the tab by testing for flag of Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI. If its the whole document, its likely from a link, or url bar, or search bar.

    So try this:

    function listener(event) {
        var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
        var url = event.subject.URI.spec;
    
        if (channel.loadFlags & Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI) {
                //the whole document of the tab is changing
                if (isToBeRedirected(url)) {
                    // replace url
                }
        }
    }
    
    exports.main = function() {
        events.on("http-on-modify-request", listener);
    }
    


    My other idea, is if you want only url bar changes. Than add an event listener to change of the url bar value. And after change if user hits enter or clicks go, then it register the observer. Then after testing for Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI than unregister the observer.