Skip to content

Instantly share code, notes, and snippets.

@Solenoden
Last active April 21, 2024 20:00
Show Gist options
  • Save Solenoden/892eb6cb5059e77950a40dd91793c48c to your computer and use it in GitHub Desktop.
Save Solenoden/892eb6cb5059e77950a40dd91793c48c to your computer and use it in GitHub Desktop.
Chromium Extension v3 Article

Chromium Extensions

Prerequisites

You will need an understanding of vanilla Javascript

Aim of this Article

The aim of this article is to give you an overview and understanding of the basic components of a Chrome Extension.

Start to finish tutorials on how to implement certain features will be available in future articles.

What is a Chromium Extension?

Chromium browsers are web browsers that are built on top of the open-source Chromium engine. These browsers include Chrome, Brave and Edge.

A Chromium Extension is a web extension built for and that is capable of running on a Chromium browser. This means you can build an extension that not only works for Chrome; which as of February 2023, has a 65.74 global market share; but also for any browsers that run on its engine.

Chromium Extension Components

Chromium extensions are essentially Javascript scripts as well as HTML pages for the extension's dialog and settings page.

The core of an extension consists of:

  • Manifest (JSON)
  • Content Script (JS)
  • Background Script (JS)

Additionally, the following are user facing components:

  • Extension Dialog (HTML + JS)
  • Settings Page (HTML + JS)
  • Context Menu

Manifest

The manifest.json file is a configuration file used by the Chromium Engine to retrieve information about your extension such as:

  • Name, desscription and version
  • Permissions which allow your extension to access Chrome APIs
  • Registered scripts and pages

Below is an example of a manifest.json file with a registered Popup page, Background Script and Content Script which can run on any page.

The manifest_version determines which version of the Chrome Extension Platform the extension is built for. When this article was written (May 2023), Manifest Version 3 is the latest version and is the required version if you want to publish your extension on the Chrome Store.

{
  "manifest_version": 3,
  "name": "Chrome Extension Demo",
  "version": "1.0",
  "permissions": ["tabs"],
  "action": {
    "default_popup": "pages/popup/popup.html"
  },
  "background": {
    "service_worker": "background-script.js"
  },
  "content_scripts": [
    {
      "js": ["content-script.js"],
      "matches": ["https://*/*", "http://*/*"]
    }
  ],
  "host_permissions": ["<all_urls>"]
}

Content Scripts

Content scripts are Javascript files that get injected into the webpage you are currently viewing. From these scripts you can execute code that alters the HTML and/or styling of the currently viewed page.

Content scripts are limited in which Chrome APIs they can access. They are for the most part limited to sending and receiving messages, working with the storage of the current page and accessing the url of the current page.

Code can be executed once the content script is loaded or you can use a publish/subscribe (pub sub) pattern to trigger certain logic when messages are sent from the extension's Popup, Background Script etc.

Background Scripts

Background scripts are also written in Javascript and unlike Content Scripts, do not run within the context of the current webpage being viewed.

While background scripts can't interact with the current webpage being viewed, they are able to access a plethora of Chrome APIs (which fire their own events), not limited to, but including:

  • Tabs
  • Storage
  • Context Menu
  • Bookmarks
  • Alarms

The type of code that you will write in the Background script is code that will take advantage of the Chrome APIs (creating alarms, reacting to bookmarks being created etc.) and registering Context Menu items if your extension requires any.

Communication Between Extension Components

Communication between the various extension components (content script, background script etc.) is done through a publisher/subscriber pattern, sending messages which can be listened for by any extension component.

chrome.runtime.sendMessage({ <MESSAGE_DATA> }) used to send messages.

chrome.runtime.onMessage.addListener(message => { ... }) used to subscribe to incoming messages.

Sending a message to a Content Script is slightly more complex since it runs on the currently viewed webpage. You will need to first query the tabs Chrome API to get the currently viewed webpages tab id, and pass it through as the first argument of the tabs.sendMessage function.

const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
chrome.tabs.sendMessage(tab.id, { type: 'COLOR_CHANGE', color: colorPicker.value });

Communication Example

Scenario: You want the user to be able to input a color value, via the extension's dialog page, which should be used to set the currently viewed page's background color.

Since you need to interact with the currently viewed page's HTML to change its background color. Since the dialog page cannot directly change the webpage's background color you will need a Content Script to do so.

When the user changes the value of the color picker on the Popup's HTML, a message needs to be sent/published using chrome.tabs.sendMessage(). Since we need to target the content script, which runs on a specific webpage/tab, the current active tab needs to be quered using chrome.tabs.query({ active: true, lastFocusedWindow: true }) so that we can pass its id in the sendMessage() function.

Sending the Message

// popup.js
document.addEventListener("DOMContentLoaded", function () {
    var colorPicker = document.getElementById("colorPicker");

    colorPicker.addEventListener("change", async function () {
        const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
        chrome.tabs.sendMessage(tab.id, { type: 'COLOR_CHANGE', color: colorPicker.value });
    });
});

Receiving the Message

// content-script.js
chrome.runtime.onMessage.addListener(function (message) {
  if (message.type === 'COLOR_CHANGE') {
    document.body.style.backgroundColor = message.color;
  }
});

Sources

Further Reading

Chrome Extensions - Part 1: Background Colour Changer

Prerequisites

You will need a basic understanding of HTML, CSS and vanilla Javascript.

Aim of the Article

The aim of this article is to introduce you to the following concepts by building a small extension that can change any web page's background colour based on user input:

  • Basics of working with extensions
  • Popup
  • Content Script
  • Communicating between the two

Instructions

Step 1: Initialization

Create your Chrome Extension project's directory and inside, create a manifest.json file. This file will be used to declare information about your extension and register a popup component and a content script.

Put the following configuration in the manifest.json file:

{
  "manifest_version": 3,
  "name": "Background Colour Changer",
  "version": "1.0",
  "permissions": [],
  "action": {
    "default_popup": "popup/popup.html"
  },
  "host_permissions": ["<all_urls>"]
}

Currently, the most important info to note is the name, which will be displayed in various places on the browser and the "default_popup" field, which registers a popup HTML file that will be created in the next step.

If you wish to learn more about the manifest file, take a look at the previous article [<TODO: INSERT LINK HERE>]

Step 2: Popup View

2.1 Create a directory called "popup" and inside, create 3 files:

  • popup.html
  • popup.css
  • popup.js

2.2 Inside the HTML file, add the following code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Background Color Changer</title>
        <link rel="stylesheet" type="text/css" href="popup.css">
        <script src="popup.js"></script>
    </head>
    <body>
        <div id="container">
            <h3 id="title">Background Color Changer</h3>
            <input type="color" id="color-picker">
        </div>
    </body>
</html>

The popup consists of a title and a colour picker input and imports the CSS and Javascript files.

2.3 In the CSS file, add the following styles:

#container {
    min-width: 180px;
}

#title {
    text-align: center;
}

input {
    display: block;
    margin: 20px auto;
}

2.4 Load and test the extension

To load the extension onto the browser, navigate to your browser's extensions page (eg; chrome://extensions). Enable developer mode in the top right hand corner and then click the "Load Unpacked" button in the top left corner and select the root folder of your project.

You will see a card with your extension's name on it. When making changes to the extension, you will need to reload it before the changes take affect.

image

To view the popup, pin the extension in the top right corner of the browser and click on the extension's icon.

image

Step 3: Changing the Page Background Colour

In order to change the background of the currently viewed page we will need a Content Script. A Content Script is a Javascript file that is inserted into the currently viewed page and is able to access the DOM to make structural and styling changes.

[<TODO: Link First Aricle on Content Scripts>]

The popup will communicate to the Content Script by sending a message when the user changes the colour on the colour picker input. The content script will listen for these messages and execute the appropriate code.

3.1 Create and Register Content Script

Create the content-script.js file in the root of the project and register the script by adding the following to the root of the manifest.json file:

"content_scripts": [
    {
      "js": ["content-script.js"],
      "matches": ["https://*/*", "http://*/*"]
    }
]

The patterns defined under the "matches" key allow the Content Script to run on any page.

3.1 Listen for Colour Change Messages

Create the content-script.js file in the root of the project and add the following code to it.

console.log('[Background Colour Changer] Content Script Loaded');

chrome.runtime.onMessage.addListener(function (message) {
    console.log('[Background Colour Changer] Content Script - Message received', message);

    document.body.style.backgroundColor = message.color;
});

The above code calls chrome.runtime.onMessage.addListener() to register code that will be called every time a message is sent. When a message is received, the background colour of the current page is set to the color value provided by the message.

Console logs are made for debugging purposes. Since the Content Script runs on the current web page, you will be able to see these logs from the current web page's console.

image

3.2 Send Colour Change Message

When the value of the colour picker on the popup is changed, a message with the new colour will need to be sent.

Add the following code to the currently empty popup.js file:

document.addEventListener("DOMContentLoaded", function () {
    const colorPicker = document.getElementById("color-picker"); // 1

    colorPicker.addEventListener("change", async function () { // 2
        const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); // 3
        const message = { type: 'COLOR_CHANGE', color: colorPicker.value };

        console.log('Popup - Sending Message', message);
        await chrome.tabs.sendMessage(tab.id, message); // 4
    });
});

Once the DOM is loaded and the Colour Picker is rendered, the following happens:

  1. The DOM is queried to get a reference to the Colour Picker input
  2. Changes on the Colour Picker are listened for
  3. The current webpage/tab is queried using the chrome.tabs API so that a message can be sent to the Content Script on that tab
  4. The message, containing any required info (in this case, the new colour) is sent to the tab, using the active tab's id

Console logs are made for debugging purposes. You will be able to see these logs by inspecting the popup and looking at its console.

3.3 Test Changes

Reload the extension by navigating to your browser's extensions page (eg; chrome://extensions), locate the card for the extension and click the reload button.

image

Next, open the browser popup, select a colour and click off the colour picker. You should now see the background colour of the currently viewed page change to the colour you selected.

image

If your implementation did not work, check the console of the webpage and popup for any errors.

Further Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment