【问题标题】:Code working in browser console but not in tampermonkey代码在浏览器控制台中工作,但不在 Tampermonkey 中
【发布时间】:2018-11-06 00:18:02
【问题描述】:

我正在尝试在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”):

没有脚本

使用脚本

我想要什么

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

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

【问题讨论】:

  • 什么是x? ??
  • 对不起,我错过了,我会更新问题。
  • 棋盘右侧的界面(您希望缺少的“GM”去的地方)不会出现在您发布的那个链接上,在任何浏览器上 - 它显示了一个移动列表相反,所以我无法重现问题
  • 在添加课程之前可能会有延迟?
  • @CertainPerformance 我正在使用最新版本的 chrome,它运行良好。

标签: javascript console tampermonkey


【解决方案1】:

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

您必须使用可识别 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

【讨论】:

  • 如果可能的话,我会投票十几次。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 2023-03-19
  • 2011-06-05
  • 2017-11-26
  • 2020-03-14
  • 1970-01-01
  • 2015-06-08
  • 2011-07-29
相关资源
最近更新 更多