Dev DIY: Automated Javascript

So, we’ve all had that one site we use all the time, but there’s just that one part that never works the way it should. Well, it’s time to say goodbye to that frustration, because if you have some familiarity with JavaScript, then I have the solution for you!

I often use the built in ‘Inspect’ tools to browse a site’s code, and will need to find a menu that does not want to cooperate, or trigger an event that refuses to fire.  Usually, this will be on a site that I need to use on a regular basis, and I would have to repeat this process frequently in order to correct the issues.  Finally I thought, “There has got to be a better way to run this script every time,” and lucky for me, there was!

After some searching, I came across the amazing browser extensions Tampermonkey for Chrome, and Greasemonkey for Firefox.  Whether it’s using these extensions to save time, or just for some good ol’ fun, you’re going to have a good time with these tools in your tool belt.

If you’ve never heard of these extensions, here’s a quick rundown:

  1. Write the script for the page you want to modify
  2. Be sure to specify the page, or domain that the script will run on
  3. The extension will then choose an appropriate break in the loading of a page to inject your script, so keep in mind when elements initialize

For an example: Say I’m in the back end of an eCommerce platform where the content view defaults to a WYSIWYG type setup.  Now, there is a setting which will change the view to render code.  All I have to do is write a short line of code that will trigger that setting, and specify when to run it using domain matching (e.g.*).  Wildcard characters work too, so in order to run on all pages, I’d use this format in the domain section:


Now, whenever I visit a matched page and the code runs, it will default to the code view, and I can even keep those preferences with a single line, e.g.:

document.getElementById("checkboxElement").checked = true;

It’s true that this might only save you a few seconds, but those seconds can add up when you use a site daily!

If you are more comfortable with using a Javascript library such as jQuery, then we can initialize it on a page fairly easily. Keeping in mind not all pages have jQuery built in, we will have to load it onto the page manually. We can do this by creating a script tag in the DOM with a src attribute pointed to the latest version of jQ.

    var script = document.createElement("script");
    script.setAttribute("src", "");
    script.addEventListener('load', myFunction(), false);

Ready to try it out? Tampermonkey for Chrome, and Greasemonkey for Firefox.  Now, go make something awesome!

Interested in starting a project?  Contact Us!