2

I am trying to learn to write user scripts that run on greasemonkey.

I have a small personal website (that no one visits) so I'm using that as my experimental tool. I want to perform a function every time there is a GET request from the page. My page has a few ajax requests, some user initiated and some timed. Initially I added an event handler for DOM node insert, but I realized there are some requests that makes no changes to the DOM elements.

So, is it possible to add a hook to web requests?

And if not, how do I approach this issue? I'm trying to display some cool stats on the page that basically logs every request with a counter and success/failure rate... all via said userscript.

ps: it's completely pointless, but I started this out of boredom during the holidays and now I can't walk away from it!

LocustHorde
  • 6,361
  • 16
  • 65
  • 94
  • Do you use the jQuery AJAX method? In case you do, there's a solution, you can define a beforeSend method - in which you have access to the settings - and settings contain type (GET, POST..) – axel.michel Dec 31 '14 at 12:10
  • @axel.michel that way I have to make changes to the actual code, plus, plus modify it on every single request, which kind of defeats the purpose.. I am trying to do it via userscript.. – LocustHorde Dec 31 '14 at 12:51
  • @LocusHorde, well it depends, you'll could use $.ajaxSetup, by which you can define rules for all requests. More on this: http://api.jquery.com/category/ajax/global-ajax-event-handlers/, otherwise you'll have to overwrite the XMLHttpRequest as Nenad suggested: http://stackoverflow.com/questions/3596583/javascript-detect-an-ajax-event – axel.michel Dec 31 '14 at 13:00
  • Thank you, looks interesting, will experiment with them and report! – LocustHorde Dec 31 '14 at 13:07

1 Answers1

2

Maybe try overriding the XMLHttpRequest open prototype:

var XMLHttpRequestOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
  console.log("XMLHttpRequest open called!");
  /* PUT WHAT YOU NEED HERE */
  XMLHttpRequestOpen.apply(this, arguments);
}

XMLHttpRequest is the mechanism by which AJAX in browsers works. The open method is always called when a request is made. By "overriding" this method, as above, you can execute some code every time a request is sent.

Nenad Vukicevic
  • 623
  • 6
  • 12