greasemonkeyuserscriptsninjakit

Using userscript GM_functions inside the page context


I want to "re-link" everything in a specific page through a XMLHTTPRequest to a local network domain. That would lead me to GM_xmlhttpRequest in GreaseMonkey/NinjaKit except that I want to run it when the link is clicked, not when the userscript actually runs...

So I have something like:

links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++) {
    oldhref = links[i].getAttribute('href');
    links[i].setAttribute('href', 'javascript:loadLink(' + oldhref + ')');
}

I understand I can either use unsafeWindow or add a script element to document to inject loadLink function.
But how can I use GM_xmlhttpRequest in loadLink?

I've looked at 0.7.20080121.0 Compatibility page but I'm not sure if that is for what I need...

I've also considered adding an iframe to the page and the modified links would load inside the iframe (triggering the userscript again), but I'd prefer a cleaner solution...


Solution

  • You almost never need to use GM functions inside the page context, and from the code posted so far, you don't need unsafeWindow in this case either.

    Also, it is not necessary to rewrite the href for what is posted so far.

    Something like this will accomplish what you want:

    var links = document.getElementsByTagName ('a');
    
    for (var J = 0, len = links.length;  J < len;  ++J) {
        links[J].addEventListener ("click", myLoadLink,   false);
    }
    
    function myLoadLink (zEvent) {
        zEvent.preventDefault();
        zEvent.stopPropagation();
    
        var targetHref = zEvent.currentTarget.getAttribute ('href');
    
        GM_xmlhttpRequest ( {
            //wtv
        } );
    
        return false;
    }
    


    Or with jQuery:

    $("a").click (myLoadLink);
    
    function myLoadLink () {
    
        var targetHref = $(this).attr ('href');
    
        GM_xmlhttpRequest ( {
            //wtv
        } );
    
        return false;
    }