这个 tampermonkey 代码有什么错误?

What is the error with this tampermonkey code?

我的目标是 http://quizlet.com/12039115/scatter 并在 2 秒内获得分数。我的计划是通过使用 setInterval/clearInterval 禁用计时器来实现。 我从某个网站上拿了一些代码并尝试根据我的目的进行调整;它失败了。现在我需要知道出了什么问题。 原始代码可以在 blog.jazzychad.net/2011/03/20/inspect-javascript-timers-greasemonkey.html 找到。当我将其加载到 Tampermonkey 并在页面上 运行 时,仅打印出 setInterval(多次):

INSPECT_TIMERS: setInterval - 100ms
quizlib.2X5g7.js:340
INSPECT_TIMERS: function (){return c.apply(b,a||arguments)}

因此,我可以看到它找到了计时器 ID。现在我需要 clearInterval()。这就是问题所在。

上面给出输出的代码:

var go = function(window){

    var oldSetInterval = window.setInterval;
    var newSetInterval = function(f,t) {
        __log("INSPECT_TIMERS: setInterval - " + t + "ms");
        __log("INSPECT_TIMERS: " + f);
        var id = oldSetInterval(f,t);
        return id;
    };
    window.setInterval = newSetInterval;
    //setTimeoutDeleted
    function __log(msg) {
        if (window.console && window.console.log) {
            window.console.log(msg);
        }
    }
};

var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + go + ')(window);';
document.body.appendChild(script); // run the script

当我添加

clearInterval(id);

紧接着

return id;    

页面确实无法响应单击以启动 "game"。我接近这个错误吗?我需要某种延迟,还是我错过了大局?

你的问题是,有多个 setInterval 调用,我这边好像有 3 个。

如果您在单击 "Start Game" 之前在您的控制台中 运行 此代码,它将记录对 setInterval 的以下调用。

var originalSetInterval = window.setInterval;
window.setInterval = function(func, intr) {
    var id = originalSetInterval.apply(window, arguments);
    console.log('----setInterval----');
    console.log('function:', func);
    console.log('interval:', intr);
    console.log('id:', id);
    console.log('-------------------');
    return id;
};

然后当你点击"Start Game",你会得到如下输出。

----setInterval----
function: function()
interval: 17
id: 10
-------------------
----setInterval----
function: function()
interval: 17
id: 12
-------------------
----setInterval----
function: function()
interval: 100
id: 13
-------------------

在继续阅读之前,请随时停止阅读并自己做一些实验。

您可能不想对所有这些调用 clearInterval。 运行 时钟的那个似乎是具有 100 间隔的那个。要在不影响其他间隔的情况下禁用该间隔,您可以使用简单的 if 语句。

var originalSetInterval = window.setInterval;
window.setInterval = function(func, intr) {
    var id = originalSetInterval.apply(window, arguments);
    console.log('----setInterval----');
    console.log('function:', func);
    console.log('interval:', intr);
    console.log('id:', id);
    console.log('-------------------');
    if (intr === 100) {
        clearInterval(id);
    }
    return id;
};

这样做将成功停止时钟。然而,一旦你完成游戏,你会发现游戏仍然会知道你花了多长时间。时钟只是一个视觉元素。

如果您想在游戏中作弊,您需要将实际计算最终分数的代码作为目标。听起来是学习如何使用浏览器的开发工具的好机会,尤其是 JavaScript 调试器(使用漂亮的打印功能使缩小的 JS 更易于阅读)。