Using JavaScript to hack the web

Not all hacking is mischief. Here's how you can use JavaScript to make your browser better.
682 readers like this.
Javascript code close-up with neon graphic overlay

Photo by Jen Wike Huger

There's no lack of online resources for JavaScript, from courses that teach you the basics to tutorials on app creation. In this article—which doesn't require you to make your own apps, or even to have particularly deep product knowledge—I'll explain how to use JavaScript to create useful browser hacks that enhance your web experiences and boost productivity.

The power of the bookmarklet

We all know how useful bookmarks are. They let you save a link to a webpage, categorize it, and add additional data (metadata) to help you find it quickly in the future and file it in a structure you can easily navigate. What many people don't know is that you can also save tiny snippets of code to these bookmarks, which are executed in the context of the web page you are on, including access to its structure and styling.

If you open the Facebook console, you'll see that its developers are very much opposed to that sort of snooping—and for good reason. Even without access to their code, you can make changes and even break some apps.

Facebook developer code - keep out

Facebook's developers don't want you messing with their console.

Still, you might forget what you typed or lose a bit of text. Or, if you're like me, the process of saving the files you open, copying them, going to the website you want, opening the console, pasting, and running seems like a lot of effort. Here's some code I use to check how long a webpage is (measured in screens on the device I'm using it). This works on Edge, Firefox, Chromium, and even my mobile:

javascript:alert(document.body.scrollHeight / window.innerHeight) 

If I know how long a page is, I can decide in advance whether I'll read it. I use it to show clients how big or small webpages are on various devices.

Here's another tool I use to remove all images and gists from programmer blog posts to get only the highlights (I also bookmark them; I'm not endorsing skimming as an alternative to reading).

javascript:(function(){ [].slice.call(document.querySelectorAll('img, .gist')).forEach(function(elem) { elem.remove(); }); })()

You'll notice that most of this code is not complicated; in fact, some of it is downright simple. Because these are primarily for my own personal use, simple is fine. If I were to put these in a gist, others could fork and update them and we might have better bookmarklets.

Persistent changes across the web using add-ons

Most of us who are not web designers don't want the hassle of multiple browsers. We also don't want our links cluttered with snippets of JavaScript. To be clear, I'm not talking about writing your own add-ons, but using existing ones to enhance your web experience.

The problem

When I first started using Reddit and Imgur, I found their gallery editing difficult. I could have stopped using the tools, but then I'd need to find another online service and upload my media. Also, I might forget and come back to Imgur and be unable to navigate my own content. My solution was to play around in the console and page inspector to see if I could get what I wanted on their service.

Imgur page inspector

Right-click and then left-click inspect element to get an instant look at the structure of a web page.

After about five minutes, I noticed tiny differences between large images and small thumbnails. I needed bigger images so I could see what I was dragging and establish some narrative order.

The solution

The code I came up with was relatively simple, with only seven lines. The point wasn't to write the least amount of code, or even the cleanest code, but to simply complete the task: Fire and forget!

(function(jQuery) {
    jQuery('.sortable-image img, .sortable-image').css({width:'auto',height:'auto'})
    jQuery('.sortable-image img').each( function(e,elem) {
        var fixedImg = jQuery(this).attr('src').replace('s.png','.png');
        jQuery(this).attr( 'src', fixedImg );
    });
})(jQuery);

First I told the web page to remove height and width constraints, then to loop through each sortable image and replace part of the filename. It's not the cleanest code; it relies on Imgur's DOM structure remaining unchanged and having the jQuery library, but the idea is to get what you need so you can continue. And it's a lot more efficient than emailing the dev team with petulant requests to change everyone's experience because you find it difficult to use.

I use an add-on for this, and as far as I know, it's not strictly OpenSource (although you do have access to the code if you can find the Chromium user-profile folder) [User JavaScript and CSS]. But it allows you to do what you want, and even implement rules for a script to run on a specific URL or URL pattern.

(Note that Imgur no longer uses the same DOM, so the code above doesn't work anymore. That is true and will remain so, for much of the code you publish in this way. It's not designed to build an empire, just to take some monotony out of your day.

Authoring add-ons

The final topic I want to address is how to create your own add-ons. I'll focus on Chromium add-ons since I have the most experience with these, but you can find links for Firefox and likely other supporting browsers on the web.

You might also want to do ambitious things like adding keyboard shortcuts to all pages with previous-next links or block out specific hate speech on the web. You can do this (browser permitting) by using or authoring add-ons for the web.

First, you need a folder to house your files.

mkdir -p ~/projects/addon-name

Once you have a place to put your files, open your favorite editor and create two files: manifest.json and content.js (the second file is specific to JS add-ons and is just a naming convention I use for content-based JS).

Manifest.json

The code for this file is the most important part of any Chromium add-on. It basically directs how and when the plug in works. Creating these professionally falls outside of the scope of this article, as does creating a Firefox extension. For more information, visit the official Chromium docs on Manifest.

{
"manifest_version": 2,
    "name": "Whatever you want to call the plugin",
    "description": "A brief description of what the plugin does. I prefer the GNU philosophy of do one thing well",
    "version": "2.0",
    "content_scripts": [
        {
            "matches": [
                "*://*/*"
            ],
            "js": [
                "content.js"
            ],
            "run_at": "document_end"
        }
    ]
}

This simply tells the browser to run content.js at the end of reading each web page for all schemes (http:, https:, etc.), on all paths.

Content.js

The code you put in your content.js is the same as any code you'd put on a web page. To navigate galleries, I use a piece of code my friend Barry generated, using an older piece of software called Album Express (it's written for Windows 7).

document.addEventListener('keyup', function(k) {
    switch(k.code) {
        case "ArrowRight":
            document.querySelector('.nav.controls .link.next').click();
            break;
        case "ArrowUp":
            document.querySelector('.nav.controls .link.up').click();
            break;
        case "ArrowLeft":
            document.querySelector('.nav.controls .link.prev').click();
            // window.history.back(); // The software Barry uses actually doesn't think to generate "prev" links, so we have to be creative
            break;
        default:
            console.log("Key Pressed:", k);
    }
});

From here:

Navigate to chrome://extensions/ in your Chromium browser

Load unpacked extension in Chromium browser

The Load unpacked extension button in Chromium.

 

Navigate to the folder in which you saved your extensions manifest.json 

Finally, click "open."

Chromium path showing extension files

Navigate to Chrome/Extensions in your Chromium browser.

Wrapping up

I hope you've enjoyed reading this article, and that it's helped you work with software projects without changing the code for everyone. If you are just getting into JavaScript, experiment before you build your own experiences.This will help you learn what patterns and methodologies work best for you.

Also, if you create something, please share it. I've spent the better part of my IT career keeping things to myself, like Gollum with his Precious. Once I started helping others and sharing my ideas, my own skills improved faster than ever. If it's a bookmarklet or a script pasted in via an existing extension, link a gist and tweet it out, or paste it in the comments below. If it's more complex, like an extension, create a GitHub repo (it's free to sign up and share code publicly, and it helps protect against data loss), paste into the comments below, and tweet or share.

Lewis Cowles, Circa 2022
I work at a fintech startup in London. I Really like pair programming, cognition and education, and repeatability. Talk to me about testing, automation, or whatever you are passionate about.

6 Comments

Great article. You make me want to learn more about Javascript.

Hi Lewis thanks for saying 'Once I started helping others and sharing my ideas, my own skills improved faster than ever. '

Great stuff, JavaScript is so limitless.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.