Search code examples
javascriptuserscripts

how can a userscript get notified about ajax-driven changes on the page?


Given items on a webpage that get changed by AJAX calls over time, how can a userscript get notified about those changes, whenever they occur?

Imagine the Facebook newsfeed. It has 12 items in it when you load the page. Those items are wrapped in <li> tags contained within a <ul>. As you scroll the page down, new <li> chunks of data load into that <ul>.

I'm wondering how a userscript could be notified of such a change.

One idea is to constantly query that <ul>, counting its items, and watching to see if that number gets bigger. Possible, but to catch the change right when it happens it might have to run so often that it's too expensive.

Another idea would be to figure out what scroll position triggers the loading, and to watch for such a change. Less expensive, but very specific.

I'm wondering if there's a third option. Something that would notify me of the change, whenever it happens. I'm not just interested in the feed, but in this concept more generally. Given items on a page that get changed by AJAX calls, how can a userscript get notified about those changes?


Solution

  • Hijack the send method

    var oldSend = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(){
        // do what you need; then send the request
        oldSend.apply(this, arguments);
    }