javascriptajaxtampermonkey

Force Tampermonkey to run/execute script late


How do I force Tampermonkey to run/execute a script late after every document loaded by AJAX?

I wish to access those elements in my script and change them. But, even though I set @run-at to document-end in the setting page, it executes while the document wasn't loaded fully. And, it happens at this specific website !!

I tried these ways but was unsuccessful:

  1. Onload event.
  2. I tried while statement to check if all documents were loaded and then continue executing my script but it crashed and fell into infinite loop.
  3. I tried console to execute a function (but inaccessible by console).

So what do I do?


Solution

  • The content you want is being loaded by AJAX, so you need to use AJAX-compensation techniques in your script.

    The easiest way to do that is to use waitForKeyElements(). Something like:

    // ==UserScript==
    // @name     _YOUR_SCRIPT_NAME
    // @include  http://YOUR_SERVER.COM/YOUR_PATH/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    
    waitForKeyElements (
        "jQUERY SELECTOR TO THE NODE(S) YOU WANT",
        changeFontColor
    );
    
    function changeFontColor (jNode) {
        jNode.css ("color", "red");
    }