代码在浏览器控制台中工作但在 tampermonkey 中不工作

Code working in browser console but not in tampermonkey

我正在尝试 运行 https://lichess.org/uZIjh0SXxnt5 上的以下代码块。

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

for(var i = 0; i < x.length; i++) {
    if(x[i].href.includes("WaisKamal") && x[i].classList.contains("user_link")) {
        x[i].innerHTML = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + x[i].innerHTML;
    }

    if(x[i].href.includes("WaisKamal") && x[i].classList.contains("text")) {
        x[i].innerHTML = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + x[i].innerHTML;
        console.log(x[i]);
    }
}

我正在使用 tampermonkey 来自动化该过程。页面加载时,第一个 if 语句 运行 正确,但第二个不正确。但是,当我从浏览器控制台 运行 第二个时,它工作正常。

下面是脚本的更详细内容(我想添加那些橙色 "GM"s):

没有脚本

用脚本

我想要的

我检查了this,但没有解决我的问题。

有什么帮助吗?提前致谢。

该页面的大部分内容是动态加载的(AJAX 驱动),这意味着您的脚本通常会在您感兴趣的节点出现之前 运行 完成 [=26] =] 页面。

您必须使用 AJAX 感知技术,例如 waitForKeyElementsMutationObserver

这里是完整的 Tampermonkey 脚本,说明了该过程:

// ==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);
}

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