Code working in browser console but not in tampermonkey

后端 未结 1 771
野的像风
野的像风 2020-12-04 00:41

I am trying to run the following block of code on https://lichess.org/uZIjh0SXxnt5.

var x = document.getElementsByTagName(\"a\");

for(var i = 0; i < x.le         


        
相关标签:
1条回答
  • 2020-12-04 01:09

    Most of that page is loaded dynamically (AJAX-driven), which means that your script will normally finish running long before the nodes, that you are interested in, appear in/on the page.

    You must use AJAX-aware techniques such as waitForKeyElements or MutationObserver.

    Here's a complete Tampermonkey script that illustrates the process:

    // ==UserScript==
    // @name     _Lichess.org, Glorify select users
    // @match    *://lichess.org/*
    // @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // @grant    GM.getValue
    // ==/UserScript==
    //- The @grant directives are needed to restore the proper sandbox.
    
    waitForKeyElements ("a[href*='WaisKamal']", spiffifyLink);
    
    function spiffifyLink (jNode) {
        var oldHtml = jNode.html ();
        var newHtml = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + oldHtml;
        jNode.html (newHtml);
    }
    

    See this other answer for more information about choosing and using waitForKeyElements and/with jQuery selectors.

    0 讨论(0)
提交回复
热议问题