我的Greasemonkey脚本如何实现页面自动重新加载和按钮自动点击?

3

我是JavaScript的初学者。我需要知道是否可能以及如何实现。

我想创建一个Greasemonkey脚本,每小时自动重新加载一个网页,然后在重新加载页面之后,希望它可以为我点击一个按钮。

这个可能吗?


是的,可以使用 addEventListenersetTimeoutclick - Jay
那我该如何开始呢?是否可以设置它在随机时间间隔内重新加载并点击? - Ryan'sDad
1个回答

6
  • For clicking stuff, see this answer.

  • See also a javascript reference for location.reload().

  • See also a better javascript reference for setTimeout().

  • Since the button may be loaded via AJAX (Need more information in the question), reference the waitForKeyElements() utility, for dealing with AJAX delays/modifications.

  • Start learning jQuery; it will save you a ton of grief and effort.

  • Identify the jQuery selector for the button you want. You can use tools like Firebug to help with this (Note that jQuery selectors and CSS selectors are mostly the same, but jQuery has more options/power).

    For example, if the page's HTML had a section that looked like this:

    <div id="content">
        <p>Blah, blah, blather...</p>
    
        <h2>Your available actions:</h2>
        <button class="respBtn">Like</button>
        <button class="respBtn">Hate</button>
        <button id="bestOption" class="respBtn">Nuke them all</button>
    </div>
    

    Then selectors for the 3 buttons might be (respectively):

    1. $("#content button.respBtn:contains('Like')");
    2. $("#content button.respBtn:contains('Hate')");
    3. $("#bestOption"); (Always use the id, if the element has one.)
把所有东西都放在一起,这是一个完整的Greasemonkey脚本,可以重新加载并点击:
// ==UserScript==
// @name     _Reload and click demo
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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 ("#bestOption", clickTargetButton);

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

//--- Reload after 1 hour (1000 * 60 * 60 milliseconds)
setTimeout (location.reload, 1000 * 60 * 60);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接