I'm a beginner in JavaScript. I need to know if this is possible and then if so, how to do it.
I'd like to create a Greasemonkey script that will automatically reload a webpage every hour, and then after reloading the page, I'd like it to click a button for me.
Is that possible?
I'm a beginner in JavaScript. I need to know if this is possible and then if so, how to do it.
I'd like to create a Greasemonkey script that will automatically reload a webpage every hour, and then after reloading the page, I'd like it to click a button for me.
Is that possible?
Share Improve this question edited Sep 19, 2012 at 3:00 Brock Adams 93.6k23 gold badges241 silver badges305 bronze badges asked Sep 18, 2012 at 15:56 Ryan'sDadRyan'sDad 411 gold badge1 silver badge5 bronze badges 2-
Yes, using
addEventListener
,setTimeout
andclick
. – Jay Commented Sep 19, 2012 at 0:16 - So how would I start this? Is it possible to set it to reload and click at a random interval? – Ryan'sDad Commented Sep 19, 2012 at 1:53
1 Answer
Reset to default 6For 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):
$("#content button.respBtn:contains('Like')");
$("#content button.respBtn:contains('Hate')");
$("#bestOption");
(Always use theid
, if the element has one.)
Putting it all together, here is a plete Greasemonkey script that reloads and clicks:
// ==UserScript==
// @name _Reload and click demo
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github./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);