How to Make a Userscript

As I mentioned in episode #1 of my podcast (¿Qué me estás container?), I recorded a video explaining how a userscript is structured, how to install it in Chrome and other browsers, and how useful this tool can be in everyday life.

Don’t forget to subscribe to the channel.

If you’d rather read, here’s a short summary:

The first step is to install a browser extension that lets us add and run these kinds of scripts. You can find them at the following links:

The second step is to learn the parts of a userscript. To do that, we’ll first look at an empty one, and then I’ll show a real example.

// ==UserScript==
// @name         New Userscript
// @namespace    https://sergiosusa.com
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://github.com/sergiosusa/my-user-scripts/edit/master/README.md
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // Your code here...
})();

The example above is divided into two parts: the “header,” or Metadata Block (delimited by the tags // ==UserScript== and // ==/UserScript==), and the rest, which is the content.

The Metadata Block contains a set of options. In this example, they are the minimum required ones. Let’s take a look at what each one does:

@name: The name of the script.
@namespace: A string that prevents scripts from colliding by name.
@version: The expected version number (0.1, 0.0.1, 1.0, etc.), which helps the browser extension update the script when a new version is available.
@description: A short description of the script.
@author: The author’s name or pseudonym.
@match: An expression that specifies which pages the script will run on.
@grant: The special permissions the script needs.

For more information about the “header” or Metadata Block, along with some examples, visit the official documentation.

The content has a fairly simple structure: it is an anonymous function that runs after the page has finished loading. This ensures that we can interact with the page without worrying that it hasn’t been rendered yet; we’ll put our code inside it.

The best way to reinforce what we’ve learned is to look at a real example. Here’s a small script I made so that anyone who wants to buy things on Amazon Spain through my referral link never has to add it manually again.

My Amazon Affiliate

Related posts