【问题标题】:Page keeps refreshing endlessly with Greasemonkey script页面使用 Greasemonkey 脚本不断刷新
【发布时间】:2017-09-11 01:06:59
【问题描述】:

我正在尝试点击 stackoverflow.com 侧边栏中的第一个收藏链接。

我找到了这个脚本,但问题是页面不断刷新。

有没有办法阻止这种行为?

// ==UserScript==
// @name     _ChromeC
// @include  *//stackoverflow.com/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design
    change introduced in GM 1.0.
    It restores the sandbox.
*/

waitForKeyElements ("#interestingTags a", actionFunction);

function actionFunction (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

【问题讨论】:

  • 第一次后卸载脚本?
  • 什么意思?
  • 什么不清楚?
  • “卸载脚本”是什么意思?每次访问stackoverlow时是否应该卸载它并重新安装它? XD
  • 我的意思是脚本不应该一直点击链接...

标签: greasemonkey


【解决方案1】:

问题在于,当您“单击该按钮”时,它会导致加载一个新页面,从而导致用户脚本再次运行,然后单击该按钮......并且循环不断重复。
(请注意,由于waitForKeyElements 的性质,每个脚本实例单击一次。脚本只是不断地重新启动。)

因此,显然您并不是真的希望每次都单击该按钮。
问题是:“您如何确定在哪些页面加载时单击该按钮以及哪些页面不予理会?

然后,您需要在脚本中添加持久性逻辑(在页面(重新)加载后仍然存在)以进行区分。

一种粗略的方法是假设如果您在最后(例如 10 秒)内单击过,则您不想再次单击。
这是 Greasemonkey 脚本中的逻辑:

// ==UserScript==
// @name     _ChromeC
// @match    *://stackoverflow.com/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_setValue
// @grant    GM_getValue
// ==/UserScript==

const delayBetweenClicks    = 10000;  //-- 10000 = 10 seconds
var   oldUnixTime           = parseInt (GM_getValue ("Last_redirect", "0"), 10);
console.log ("oldUnixTime: ", oldUnixTime);

waitForKeyElements ("#interestingTags a", clickOnlyOccassionally);

function clickOnlyOccassionally (jNode) {
    var currentTime = (new Date() ).getTime ();

    // Only click if we haven't done so in a while...
    if ( (currentTime - oldUnixTime) > delayBetweenClicks) {
        GM_setValue ("Last_redirect", `${currentTime}`);  //  Must store as string.

        var clickEvent  = document.createEvent ('MouseEvents');
        clickEvent.initEvent ('click', true, true);
        jNode[0].dispatchEvent (clickEvent);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2020-10-08
    • 2014-10-18
    • 2019-10-14
    • 2019-02-01
    相关资源
    最近更新 更多