2

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...

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Ok, so I managed to get that GreaseMonkey official workaround working (dunno what I did wrong the first time) with:

unsafeWindow.loadLink = function(href) {
    setTimeout(function(){
        GM_xmlhttpRequest({
            //wtv
        });
    },0);
}

But I'd still prefer a solution without using unsafeWindow if there is one... (especially since this one feels so wrong...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.