Search code examples
javascriptjquerytampermonkeyuserscripts

Function doesn't count the amount of elements correctly


I use waitForKeyElements function by Brock Adams to create the checkboxes after the links on the https://www.google.com/.

For some reason, the function works incorrectly. Instead of placing the single checkbox after each link, it counts all the links, and then add the corresponding amount of checkboxes after each of them.

What could be the error?

// ==UserScript==
// @grant   none
// @match   https://*.google.*/
// @name    Google.com
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// @require https://gist.githubusercontent.com/BrockA/2625891/raw/9c97aa67ff9c5d56be34a55ad6c18a314e5eb548/waitForKeyElements.js
// ==/UserScript==

(function() {
    'use strict';

    function test() {
        var links = document.querySelectorAll('a');
        var i;
        for (i = 0; i < links.length; i++) {
            var input = document.createElement('input');
            input.type = 'checkbox';
            links[i].parentElement.appendChild(input);
        }
    }

    //waitForKeyElements('a', test); // works incorrectly. The third parameter
        // doesn't help.
    //setTimeout(test(), 3000); // works OK
})();

The function itself:

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

    Usage example:

        waitForKeyElements (
            "div.comments"
            , commentCallbackFunction
        );

        //--- Page-specific function to do what we want when the node is found.
        function commentCallbackFunction (jNode) {
            jNode.text ("This comment changed by waitForKeyElements().");
        }

    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;
}

Solution

  • You didn't provide your use case of waitForKeyElements, but if I understand correctly, you pass the test function to it. If that's the case - no wonder it appends X checkboxes to every link on the page. Look closely:
    - Your function, upon being called, searches for all the links in the page and add a checkbox next to it
    - waitForKeyElements calls that function for every element it finds based on the selector provided. So, basically, if the page has 50 links, if will append one checkbox after every link 50 times.

    The solution is to not loop over in your function, but add a checkbox only once, to the argument provided:

    (function() {
        'use strict';
    
        function test(element) {
            var input = document.createElement('input');
            input.type = 'checkbox';
            element.parent().append(input);
        }
    })();