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!

4
  • 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..) Commented Dec 31, 2014 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.. Commented Dec 31, 2014 at 12:51
  • @LocusHorde, well it depends, you'll could use $.ajaxSetup, by which you can define rules for all requests. More on this: api.jquery.com/category/ajax/global-ajax-event-handlers, otherwise you'll have to overwrite the XMLHttpRequest as Nenad suggested: stackoverflow.com/questions/3596583/… Commented Dec 31, 2014 at 13:00
  • Thank you, looks interesting, will experiment with them and report! Commented Dec 31, 2014 at 13:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.