37

I am working on a user script and I've just found that the script is not run when the main page makes AJAX requests.

Is there any way to fire the user script both on main page load and on AJAX requests?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
LooPer
  • 1,459
  • 2
  • 15
  • 24

2 Answers2

74

The smart way to rerun the script's code on AJAX requests, is to focus on the key bits of the page and check for changes.

For example, suppose a page contained HTML like so:

<div id="userBlather">
    <div class="comment"> Comment 1... </div> 
    <div class="comment"> Comment 2... </div> 
    ... 
</div>

and you wanted the script to do something with each comment as it came in.

Now you could intercept all AJAX calls, or listen for DOMSubtreeModified(deprecated), or use MutationObservers, but these methods can get tricky, finicky, and overly complicated.

A simpler, more robust way to get ajax-ified content on a wild page is to poll for it using something like the waitForKeyElements function, below.

For example, this script will highlight comments that contain "beer", as they AJAX-in:

// ==UserScript==
// @name            _Refire on key Ajax changes
// @include         http://YOUR_SITE.com/YOUR_PATH/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

function highlightGoodComments (jNode) {

    //***** YOUR CODE HERE *****

    if (/beer/i.test (jNode.text () ) ) {
        jNode.css ("background", "yellow");
    }
    //...
}
waitForKeyElements ("#userBlather div.comment", highlightGoodComments);

/*--- waitForKeyElements():  A utility function, for Greasemonkey scripts,
    that detects and handles AJAXed content.

    IMPORTANT: This function requires your script to have loaded jQuery.
*/
function waitForKeyElements (
    selectorTxt,    /* Required: The jQuery selector string that
                        specifies the desired element(s).
                    */
    actionFunction, /* Required: The code to run when elements are
                        found. It is passed a jNode to the matched
                        element.
                    */
    bWaitOnce,      /* Optional: If false, will continue to scan for
                        new elements even after the first match is
                        found.
                    */
    iframeSelector  /* Optional: If set, identifies the iframe to
                        search.
                    */
) {
    var targetNodes, btargetsFound;

    if (typeof iframeSelector == "undefined")
        targetNodes     = $(selectorTxt);
    else
        targetNodes     = $(iframeSelector).contents ()
                                           .find (selectorTxt);

    if (targetNodes  &&  targetNodes.length > 0) {
        btargetsFound   = true;
        /*--- Found target node(s).  Go through each and act if they
            are new.
        */
        targetNodes.each ( function () {
            var jThis        = $(this);
            var alreadyFound = jThis.data ('alreadyFound')  ||  false;

            if (!alreadyFound) {
                //--- Call the payload function.
                var cancelFound     = actionFunction (jThis);
                if (cancelFound)
                    btargetsFound   = false;
                else
                    jThis.data ('alreadyFound', true);
            }
        } );
    }
    else {
        btargetsFound   = false;
    }

    //--- Get the timer-control variable for this selector.
    var controlObj      = waitForKeyElements.controlObj  ||  {};
    var controlKey      = selectorTxt.replace (/[^\w]/g, "_");
    var timeControl     = controlObj [controlKey];

    //--- Now set or clear the timer as appropriate.
    if (btargetsFound  &&  bWaitOnce  &&  timeControl) {
        //--- The only condition where we need to clear the timer.
        clearInterval (timeControl);
        delete controlObj [controlKey]
    }
    else {
        //--- Set a timer, if needed.
        if ( ! timeControl) {
            timeControl = setInterval ( function () {
                    waitForKeyElements (    selectorTxt,
                                            actionFunction,
                                            bWaitOnce,
                                            iframeSelector
                                        );
                },
                300
            );
            controlObj [controlKey] = timeControl;
        }
    }
    waitForKeyElements.controlObj   = controlObj;
}

Update:

For convenience, waitForKeyElements() is now hosted on GitHub.

This answer shows an example of how to use the hosted function.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • I apologise, the errors actually lie with zeroclipboard, not your function. An interesting thing I discovered while debugging is that if `bWaitOnce` is set to `true` the code actually fires twice, not sure if that was intentional or not – RozzA Sep 06 '12 at 03:04
  • @RozzA, I'd be interested to see code that demonstrates that. Parts of the code may fire twice (or many times) -- by design. But the `actionFunction` should only fire once per given node. – Brock Adams Sep 06 '12 at 03:10
  • 1
    @BrockAdams, why `setInterval` and not `MutationObserver`? – Iulian Onofrei Mar 05 '14 at 12:44
  • @IulianOnofrei, at the time of this answer, MutationObserver was not available, IIRC, and mutation events (now deprecated) were kludgey. The Interval code is much simpler. It also doesn't bog down Firefox like MutationObserver seems to sometime do. waitForKeyElements works well in scores of scripts I've deployed. I've only felt the need to use MutationObserver exactly twice (not counting SO answers), so haven't had any cause to retool waitForKeyElements so far. – Brock Adams Mar 05 '14 at 13:24
  • @BrockAdams, Oh, I see. I started using `MutationObserver`s since reading about them not too long ago, and I think they're fast too, but I'm not sure. – Iulian Onofrei Mar 05 '14 at 13:34
2

Another way — simpler and smaller but less flexible — is to use a JavaScript time delay to wait for the AJAX/jQuery to load and finish. For example, if the following HTML was dynamically generated after first load:

<div id="userBlather">
    <div class="comment"> Comment 1... </div> 
    <div class="comment"> Comment 2... </div> 
    ... 
</div>

Then a greasemonkey script like this would be able to modify it:

// Wait 2 seconds for the jQuery/AJAX to finish and then modify the HTML DOM
window.setTimeout(updateHTML, 2000);

function updateHTML()
{
    var comments = document.getElementsByClassName("comment");
    for (i = 0; i < comments.length; i++)
    {
        comments[i].innerHTML = "Modified comment " + i;
    }
}

See guidance here: Sleep/Pause/Wait in Javascript

Community
  • 1
  • 1
Mr-IDE
  • 7,051
  • 1
  • 53
  • 59