Categories
Javascript Programming

JavaScript userscripts

Problem

I was playing a browser-based game that required me to perform an action at 04:00. And I wanted to be asleep at 4am.
One thing I want all budding web developers to remember is this- your application front end is running on someone else’s computer. In what is effectively a debug environment. Developers need to ensure there is no trust between the client and the server (the other way around is fine, however).
Because the code is not compiled, it is even easier to dig into the code- the HTML and JavaScript -and make changes.
But I didn’t need to go that far.
Using Firefox, and hitting Ctrl-Shift-K, brings up the Web Console. From here, we can look at messages, errors and warnings, but we can also issue commands in JavaScript.

Solution

[code lang=”js”]setTimeout(function() {document.getElementsByName("act_use")[0].click()}, 120*60*1000);[/code]
Let’s break it down. First, I need to trigger something in the future. That calls for setTimeout() (setInterval() if we wanted to keep triggering again and again).
setTimeout() takes two arguments, which we might call what and when. what needs to be a function- not the result of a function, but a reference to a function, and if you won’t be using it elsewhere, you might as well inline it, as above. The when is the delay time in milliseconds.
The function body will contain all the instructions we want to carry out. I wanted to simulate a button press on a button element. So the next step is to get a reference to that element. Looking at it, I could see it hadn’t got an id attribute, but it did have a unique value for its name attribute. So that indicates use of document.getElementsByName(). Note that it is “Elements” and not “Element”, because name isn’t necessarily unique on a page. So it returns an array, of which I wanted just the zeroth element- so my call needs the index [0] suffixed to it:
[code lang=”js”]document.getElementsByName("act_use")[0][/code]
This expression should now be a reference to the button element. And what did I want to do with it? Click it. Luckily, there is a function available to us, click(). We can just tack that onto the end, and that’s all our function needs to do.
There’s not much to say about the delay, but note how I have used an expression, not just a literal. That’s to allow me to edit it more easily in future. The 120 is the number of minutes, and I can change it directly, as opposed to working out how many milliseconds it would be.
So, leaving my computer awakw, and the browser open, I issued the command in the Web Console, and came back down in the morning to find it had worked like a charm. Itch, scratched.
If you want to explore this further, might I recommend you take a look at GreaseMonkey or TamperMonkey, for permanent scripting you can apply to pages you visit?

Leave a Reply

Your email address will not be published. Required fields are marked *