Tampermonkey 中的状态操作

State manipulation in Tampermonkey

我在管理用户脚本状态时遇到了一个不寻常的问题。我希望我的脚本在计数器低于 50 秒时按下按钮,但我完全不知道该怎么做。我想我必须添加某种类型的事件侦听器,但我不知道添加哪一个以及如何添加。

let time = 60;
const counter = document.querySelector('.counter');
const result = document.querySelector('.result');

result.addEventListener('click', () => {
    console.log('done')

})

window.setInterval(function () {
    if (time > 0)
        time--;
    counter.innerHTML = time + " seconds";
    if (time <= 0)
        time = 60;
}, 1000);
 <span class="counter">60 seconds </span>
    <button class="result">Console log</button>

Tampermonkey 脚本:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://127.0.0.1:5500/index.html
// @icon         https://www.google.com/s2/favicons?domain=0.1
// @grant        none
// ==/UserScript==

(function() {
const result = document.querySelector('.result');
const counter = document.querySelector('.counter');

      if (counter.textContent === '50 seconds') {
        result.click()
    }

})();

我能看出问题所在,但我无法独自处理。如果有任何不清楚的地方,请随时询问:)

为此,您可以像这样使用 MutationObserver

// Your code for the counter
let time = 60;
const counter = document.querySelector('.counter');
const result = document.querySelector('.result');

result.addEventListener('click', () => {
    console.log('done')
})

window.setInterval(function () {
    if (time > 0)
        time--;
    counter.innerHTML = time + " seconds";
    if (time <= 0)
        time = 60;
}, 1000);

// The userscript:
// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://127.0.0.1:5500/index.html
// @icon         https://www.google.com/s2/favicons?domain=0.1
// @grant        none
// ==/UserScript==

function main() {
    const result = document.querySelector(".result");
    const counter = document.querySelector(".counter");

    // the observer
    var observer = new MutationObserver((e) => {
        if (counter.textContent === "50 seconds") {
            result.click();
        }
    });
    observer.observe(counter, {
        childList: true
    });
}
// wait until the document has finished loading
// You could also set @run-at to "document-end"
if (["interactive", "complete"].includes(document.readyState)) main();
else document.addEventListener("DOMContentLoaded", main);
<span class="counter">60 seconds </span>
<button class="result">Console log</button>