Tampermonkey Tutorial (2)

At work, I’m currently working on a rather large form. And when I say large, I mean seriously large – I just counted, it has 136 fields.

Now when a user submits the form, the input is validated. If everything is correct the user’s data is saved to a data base, otherwise the form re-renders, displaying appropriate error messages.

I have written unit tests to test the form’s logic, but nonetheless I still want to test the form manually, just to be 100% sure that things are displaying as expected.

But there’s no way that I’m going to manually fill out 136 fields over and over again. No Sir! A much better solution would be to use Tampermonkey to do it for me.

So that I can demonstrate how to do this, we’re going to need a simple form.

Here’s one I made earlier:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Tampermonkey form auto-fill</title>
    <style>
      label{ display: inline-block; margin:5px 0px; }
    </style>
  </head>

  <body>
    <form>
      <div>
        <label for="name">Your name:</label>
        <input type="text" id="name">
      </div>
      <div>
        <label for="email">Your email:</label>
        <input type="text" id="email">
      </div>
      <div>
        <label for="comments">Your comments:</label><br>
        <textarea id="comments" rows="15" cols="50"></textarea>
      </div>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Were also going to need to install Tampermonkey (a userscript manager for Blink-based Browsers such as Chrome and Opera). Luckily, my previous Tampermonkey tutorial explains how to do this.

Now, with Tampermonkey installed, click on the Tampermonkey icon in the top right hand corner of your browser, then select Add a new script …. A new tab will open which looks like this:

Tampermonkey screenshot - create new script

So, let’s fill those details out. They’re all fairly self explanatory, except perhaps line 6 (which begins ‘@match’). Here, using a regular expression, you can specify a full or partial url. When this regular expression matches your current url, Tampermonkey will fire the script.

// ==UserScript==
// @name Auto-fill my massive form
// @namespace http://hibbard.eu/
// @version 0.1
// @description Autofills fields in my massive form
// @match http://hibbard.eu/*
// @copyright 2013+, hibbard.eu
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==

As you can see, I have specified that this script should run when I visit any page beginning with http://hibbard.eu/. Obviously, anyone following this tutorial will need to adapt this path accordingly.

Also worthy of note is the fact that I have required the latest version of jQuery in the final line.

So, with that out of the way, we can get on to the exciting bit, writing the script.

Let’s start off by adding a button to the page and attaching some click behaviour to it:

$('body').prepend('
  <input type="button" value="Populate" id="populate">
');

$("#populate").on("click", function() {
  console.log("I was clicked");
});

To populate the form, I am going to create an object-literal whose properties correspond to the ids of the respective form fields. Then, when the user clicks the populate button, I am going to set the values of the form fields to the value of the corresponding attribute.

var values = {
  name: "Fred Blogs",
  email: "freddyboy@gmail.com",
  comment: "Your tutorial is simply the best!"
}

$('body').prepend('
  <input id="populate" type="button" value="Populate"/>
');

$("#populate").on("click", function(){
  Object.keys(values).forEach(function(key){
    $("#" + key).val(values[key]);
  });
});

And that’s it! Now, when you visit the page with the form on, you will see a button, that when clicked, will auto-fill your form for you – quite pointless in this small example, but when you have 136 form fields to deal with, it’s pretty cool!

As a side note, in the above code we are combining Object.keys() and Array.prototype.forEach() to iterate over the object’s attributes.

You can read more about this here: How to Loop through JavaScript object literal with objects as members?

So, I hope this tutorial was useful for people. I noticed in my analytics that I’m getting a lot of traffic for “Tampermonkey tutorial”, so if there is some aspect of this extension that I didn’t cover, that people would like to learn about, be sure to let me know in the comments.


This post currently has 16 responses

  1. stefan says:

    these tutorials are wonderful. I just wish there were dozens more. thank you!

    • hibbard.eu says:

      Thanks for that. Anything you would like to see a tutorial on?

      • Gareth says:

        I’d love to see: replacing an element in a page with something (say a picture from a different website)

        • admin says:

          Hi Gareth,

          That should be possible.
          If you head to http://community.sitepoint.com, open an account (you can log in with a bunch of services), then start a thread in the JavaScript forum, we can discuss it there.
          Send me a message via Twitter/contact form when you have done this and I’ll answer you on SitePoint.

  2. pyromaniac_14 says:

    How do you create a script that will constantly end the hapara remote control teacher dashboard in task manager on a chromebook?

    • hibbard.eu says:

      To be honest, no idea.
      What have you tried?

      Plus, what do you mean by “constantly end”?

      • pyromaniac_14 says:

        if you go to task manager on chrome and you select something then click on end process it will make it crash when i do it for the hapara remote control teacher dashboard it will come back after a few seconds so i want a script that will keep selecting it then ending it

        • hibbard.eu says:

          I don’t own a Chromebook, so I have no idea if this is possible. Sorry.

  3. J Siggy says:

    How do you write a script for buying something online or just adding to cart for purchase?

    • hibbard.eu says:

      You can use Tampermonkey to simulate a click on an “Add to Cart” button, or you can use it to enter values in a form, then programatically submit it.

      The implementation details would depend on what the form in question looked like.

  4. Franc Gonz says:

    Hi there,

    Thanks for your tutorial.

    I am trying to get this script work on this site form fill and can’t get it work.

    https://www.saga.co.uk/insurance/car-insurance/get-quote/Vehicle

    Could you help me figure out what I am doing wrong please.

    Kind Regards.

    • admin says:

      Sure I can try and help you, but the comments section of a blog is a bad place to do so.

      Instead, head to http://community.sitepoint.com, then register an account (or log in with FaceBook, Google or Twitter) and post your question in the JavaScript forum.

      Once you have done that let me know and I’ll answer you there.

  5. Michael says:

    I’d be interested to know how to find elements with a fixed pixel width and change them to a percentage one. For example, if an element is defined to be over 800px wide, change it to 100%.

    Any ideas where to start?

    • admin says:

      Sure. Something like this should get you going:

      $("*").each(function(){
        console.log(this + ": " + $(this).width() + "px");
      });
      
  6. Jack says:

    Would this work for auto filling craigslist posts?

Comments are closed!