Developing your own Chrome Extension - The Theory (Part 1)
Tags: chrome, javascript, webdev, ai
Published: 2024-03-02 21:21:52

Google Extensions are powerful tools that enhance Chromium-based Web browsers' functionality and customization options. From blocking ads and managing passwords to organizing bookmarks and adding new functionalities to web applications, Google Extensions offers a wide range of solutions to cater to the needs and preferences of individual users.

A great place to start learning about Google Extensions is their web page. However, I've noticed that their code snippets have several bugs. Furthermore, if you prefer to work with Typescript, you'll find that there aren't any tutorials available on the topic. That's why I've started this series about developing a Chrome extension myself.

## Why do I want to Develop a Google Extension?

I have an issue with the numerous newsletters that I receive. Although the titles sound interesting, I don't have enough time to read all of them. 

I devised an idea to preview a summary by hovering over the link. I know that Arc Max can perform this function (I had this idea a long time ago 🫢), but it requires using Arc's browser.

In this blog post, we will create a Chrome extension allowing you to preview a link. This is A significant advantage because it will work on all Chromium-based browsers.

## Anatomy

Let’s understand how an extension is structured and what files must start.

### Manifest v3

The manifest is **a file that defines an extension**. It provides the extension's metadata and configuration. With their latest version, v3, you can run background tasks with [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers), which can also be used without a network connection by caching assets[^1]. Furthermore, they add more APIs[^2].

#### Structure

You define the manifest in a `manifest.json`

```json
{
  "manifest_version": 3,
  "name": "Minimal Manifest",
  "version": "1.0.0",
  "description": "A basic example extension with only required keys",
  "icons": {
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  }
}
```

But to make it interactive via HTML or JavaScript, the manifest contains different key values to call the correct files.

`content_scripts`

This feature lets you add static JavaScript or CSS to the current page. You can select the specific pages where the script should run. It can manipulate the DOM, interact with page content, and listen to page events while modifying its appearance.

![Content Script Explanation](https://assets.vrite.io/646ce5fc07ef9ba4530fd23b/oAA6w4I-qJVxfmHe8oJlo.png)

```json
{
  "manifest_version": 3,
  "name": "Run script automatically",
  "description": "Runs a script on www.example.com automatically when user installs the extension",
  "version": "1.0",
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  },
  "content_scripts": [
    {
      "js": [
        "content-script.js"
      ],
      "css": ["my-styles.css"],
      "matches": [
        "http://*.example.com//"
      ]
    }
  ]
}
```
- But: Limited access to extension APIs
- But: Runs in the context of each page can cause conflicts

More information [here](https://developer.chrome.com/docs/extensions/reference/manifest/content-scripts).

`background`

The `background` key is used to specify a javascript file as the extension service worker. A service worker is a background script that acts as the extension's primary event handler. It can handle long-running processes, event handling, and communication with other extensions. Furthermore, it has a broader extension API and browser functionality[^3]

![Background Javascript explanation](https://assets.vrite.io/646ce5fc07ef9ba4530fd23b/gVRMoUn27BhTJzuq5sRwZ.png)

```json
{
  ...
   "background": {
      "service_worker": "service-worker.js",
      "type": "module"
    },
  ...
}
```
- But: It runs continuously and may consume resources
- But: Cannot directly interact with web page content

There are many other fundamental values, but `content_scripts` and `background` ensure interactivity. Check all the other keys [here](https://developer.chrome.com/docs/extensions/reference/manifest).

### Storage

Another essential part is the storage. You can store data using [Local Storage](https://developer.mozilla.org/docs/Web/API/Window/localStorage), [Session Storage,](https://developer.mozilla.org/docs/Web/API/Window/sessionStorage) or [IndexedDB](https://developer.mozilla.org/docs/Web/API/IndexedDB_API). This way, data will be retained even if the user clears browser data. However, the Local Storage and Session Storage can only be accessed from the `content_script` whereas Service workers can only access IndexedDB and [Cache Storage](https://developer.mozilla.org/docs/Web/API/CacheStorage).

If you develop an extension that contains a content script and service worker, then it’s recommended to use IndexedDB (it’s inbuilt-browser storage, so it should be available).

For more information, click [here](https://developer.chrome.com/docs/extensions/develop/concepts/storage-and-cookies).

## Conclusion

In the first part of this series, we learned why I created it and the structure of the Google Chrome Extension manifest file. It explains the basic anatomy of an extension, including the manifest file, which defines metadata and configuration. The manifest contains keys like `content_scripts` and `background` to specify JavaScript files that allow interactivity.

[^1]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

[^2]: https://developer.chrome.com/docs/extensions/develop/migrate/api-calls

[^3]: https://blogs.lakebrains.com/difference-between-content-script-background-script-pop-script-option-script/