World News

How to make your first WebExtension that works in Chrome, Firefox, and beyond

https://www.profitableratecpm.com/f4ffsdxe?key=39b1ebce72f3758345b2155c98e6709c

Cross-browser extensions are easy to write, thanks to the WebExtension initiative and core Web technologies. Using a common format, you can write extensions that work anywhere, without the need to target specific browsers.

Find out how to code and test your first extension to make custom changes to any web page.

What are WebExtensions?

WebExtensions are cross-browser extensions that use web APIs to enhance the default functionality of web browsers. Extensions are distributed as source code and use the core web technology stack: HTML, CSS, and JavaScript.

While extensions have been around for nearly 30 years, browsers have traditionally used different approaches to support them. This meant that a Chrome extension wasn’t compatible with the Firefox browser, and vice versa. Thanks to standardization efforts—and the consolidation of many browsers around the Chromium engine—this is now less of a problem. Since 2021, the WebExtensions initiative has aimed to formalize the ecosystem. In ideal circumstances, this lets developers write an extension once and make it available for all browsers.

Read on to find out how to develop modern, cross-browser extensions using the web platform; it’s easier than you think!

Although WebExtensions aims to be browser-neutral, Firefox is the easiest browser to develop them with, as it lets you load an extension temporarily. At the other end of the scale, Safari requires a paid developer subscription.

Writing a manifest file

The one thing that every extension needs is a manifest file to describe its overall structure. Here’s an example:

{
    "manifest_version": 3,
    "name": "my first extension",
    "version": "1.0",
    "icons": {
        "16": "app/images/icon16.png",
        "48": "app/images/icon48.png",
        "128": "app/images/icon128.png"
    },
    "permissions": [
        "webNavigation",
        "storage"
    ],
}

This file is in JSON format, meaning you can use any of the many tools available to edit or view it.

Only three keys are required: name, version, and manifest_version. The name and version keys are specific to your app, and the actual values don’t matter too much for this tutorial. Chrome will refuse to load your extension if the version is invalid, though, so make sure it’s 1-4 dot-separated integers, like “0” or “0.0.1”.

The manifest_version is a bit of a sore point: while other browsers may support versions 1 and 2, Chrome will refuse to load an extension unless it uses version 3. Using this version cedes a bit of control, but if you want Chrome support, you’ll have to go with it.

Beyond that, a manifest file can use many other keys to describe the nature of your extension. These include author, description, and icons, which may all be useful to advertise your extension in a store. The commands key lets you define keyboard shortcuts.

One of the most useful manifest keys is content_scripts, which lets your extension load JavaScript or CSS files and apply them to a web page:

"content_scripts": [{
    "matches": ["https://en.wikipedia.org/wiki/*"],
    "js": ["script.js"],
    "css": ["style.css"]
}]

Each object in content_scripts must contain a matches key, which defines the URLs your extension runs on. The js and css keys let you list scripts or style sheets that the extension should load when you’re viewing a matched page.

Writing your extension code

This simple example will imitate Tampermonkey, a popular extension that lets you customize web pages. Using Tampermonkey, you can do things like fix Reddit’s feed to avoid the “Best” view.

With a manifest file and a bit of JavaScript, you can easily write a simple web extension. This sample will alter your view of Wikipedia pages, but the world really is your oyster here; anything you can do with a web page is available.

{
    "manifest_version": 3,
    "name": "tweakipedia",
    "description": "Tweak Wikipedia pages to our liking",
    "version": "1.0",

    "content_scripts": [{
        "matches": ["https://en.wikipedia.org/wiki/*"],
        "js": ["tweakipedia.js"],
        "css": ["tweakipedia.css"]
    }]
}

I’ll start simply, with some CSS to change a couple of things to suit my personal preference. For one thing, I don’t like the “more citations needed” notice; as a casual reader, it just adds noise. So I’ll hide that by identifying the element’s class and setting its display to none:

.box-More_citations_needed { display: none; }

If you’re feeling uncharitable, you could also hide the fundraising notice:

.cn-fundraising { display: none; }

Next, I find the footnote markers a bit distracting, so I’ll deemphasize them a bit by modifying their color:

sup a { color: rgb(51, 102, 204, 0.5); }

Note that this is the default color with a 50% alpha channel, meaning that it’s semi-transparent. This helps to tone down the weight of these marks.

Taking this concept one step further, I’d like to hide (or modify) other elements, but only on demand, and with a way of easily undoing the change. This requires a bit of JavaScript—but only a tiny bit!

toggle_on_key("Escape", "sup a,.mw-editsection,.vector-page-toolbar");

function toggle_on_key(key, sels) {
    document.addEventListener("keydown", function (ev) {
        if (ev.key === key) {
            document.querySelectorAll(sels).forEach(function (node) {
                node.style.display = node.style.display === "none" ? "" : "none";
            });
        }
    });
}

I’ve created a convenience function to hide/reveal given elements when a given key is pressed. The event handler simply looks for a matching key, then finds all elements that match a selector, and either hides or reveals them depending on their current visibility. This uses the exact same CSS property (display) as the style sheet; it just uses JavaScript to apply it dynamically.

Installing and using your extension

With everything in place, it’s time to install your extension and try it out.

In Firefox, go to about:debugging, select “This Firefox” from the left menu, and click the “Load Temporary Add-on” button. Select any of your files (your manifest or any script file) and open it.

Firefox's extension page with a temporary extension loaded.

In Chrome, go to chrome://extensions/, enable Developer mode using the toggle in the top-right, then click the “Load unpacked” button in the top left. Select the directory containing your extension’s files.

Chrome's extension page with an unpacked extension loaded.

You should be able to see the extension working on any Wikipedia page. It should change the look of a page from this:

A wikipedia page shows a note about additional citations.

When the extension’s installed and enabled, such a Wikipedia page should look like this, with the prominent notification hidden and footnote links in a lighter color:

A wikipedia page without the note about additional citations.

Related Articles

Leave a Reply

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

Back to top button