Chrome Extension 101: Beginner's Guide

Welcome! Whether you're here to learn the basics of Chrome extension development due to a client requirement, to promote your brand, or simply to explore this fascinating area of programming, you're in the right place. This blog will guide you through the fundamentals of building a Chrome extension.

The motivation behind writing this blog comes from the limited number of resources available online that clearly explain the basics of Chrome extension development. Recently, I developed a Chrome extension called Scroll Master, which automatically scrolls web pages based on specified intervals and distances in pixels. During the development process, I encountered numerous challenges due to the scarcity of helpful articles and the complexity of the code structure.

To contribute to the developer community and help others avoid the same pitfalls, I decided to write this article. Here, you'll find a straightforward explanation of how to build a Chrome extension. For further details, you can also refer to the official Chrome extension documentation.

Introduction

What is Chrome Extension?

A Chrome extension is a small software program that customizes the browsing experience. It can modify and enhance the functionality of the Chrome browser by using web technologies like HTML, CSS, and JavaScript.

Why Develop Chrome Extensions?

  • Customization: Tailor the browser to meet specific needs.

  • Productivity: Automate repetitive tasks.

  • Enhancement: Add new features to websites or the browser itself.

Getting Started

1. Setting Up Your Development Environment

  • Tools Needed: A text editor (like VS Code), Chrome browser, and basic knowledge of HTML, CSS, and JavaScript.

  • Directory Structure: Create a new folder (In my case: My Chrome Extension) for your extension project.

2. Creating the manifest.json file

The manifest.json file is the blueprint of your extension. It includes essential metadata such as the name, version, permissions, and the files used by the extension.

{
  "manifest_version": 3,
  "name": "My First Extension",
  "version": "1.0",
  "description": "A simple Chrome extension example.",
  "permissions": ["storage"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

Explanation

  1. "manifest_version"

    • Specifies the version of the manifest file format being used. Manifest version 3 (MV3) is the latest and includes improvements in security, privacy, and performance.
  2. "name": "My First Extension"

    • The name of your extension as it will appear in the Chrome Web Store and the browser's extension manager.
  3. "version": "1.0"

    • The version number of your extension. This is important for version control and updates. It follows the semantic versioning format (major.minor.patch) e.g. (2.1.1).
  4. "description": "A simple Chrome extension example."

    • A brief description of what your extension does. This appears in the Chrome Web Store and helps users understand the purpose of your extension.
  5. "permissions": ["storage"]

    • Specifies the permissions your extension needs. In this case, the storage permission allows your extension to use Chrome's storage API which has .

    • There are many permissions you can input here

      Please check official docs of Google Web Store

    • Important Note: Only request permissions that are necessary for your extension's functionality to avoid rejection during the review process.

  6. "action": { "default_popup": "popup.html", "default_icon": "icon.png" }

    • Importance: Defines the default action for your extension's toolbar button.

      • default_popup: Specifies the HTML file to be displayed as a popup when the extension's icon is clicked.

      • default_icon: Specifies the icon file for the extension's toolbar button.

  7. "background": { "service_worker": "background.js" }

    • Importance: Defines the background script for your extension.

      • service_worker: Specifies the JavaScript file that runs in the background, handling events and performing tasks that don't require a user interface.
  8. "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ]

    • Importance: Specifies the content scripts that run in the context of web pages.

      • matches: An array of URL patterns that the content script should be injected into. "<all_urls>" means the script will run on all web pages.

      • js: An array of JavaScript files to be injected into the matching web pages.

Each of these lines plays a crucial role in defining the behaviour, permissions, and user interface of your Chrome extension. If you have any more questions or need further clarification, feel free to ask!

Important Note: Ensure that you only include necessary permissions in the permissions array. If you list permissions for services, you are not using, the Google Chrome Web Store team may reject your extension during the publication process. This step is crucial for maintaining security and compliance with Chrome Web Store policies.

3. The three primary components of a Chrome extension (popup.html, background.js and content.js):

1. popup.html

The popup.html file defines the user interface that appears when the user clicks on the extension's icon in the browser toolbar. It's essentially a simple web page that can contain HTML, CSS, and JavaScript.

Example popup.html:

HTML

<!DOCTYPE html>
<html>
<head>
  <title>My Extension Popup</title>
</head>
<body>
    <h3>Tab Scroll & Rotate</h3>
    <button id="loadTabs">Open Saved Tabs</button>
    <button id="addLink">Add Links</button>
</body>
</html>

2. background.js

The background.js file defines the background script that runs continuously in the background, even when the browser is closed. It's used for tasks like:

  • Persistent tasks: Tasks that need to run indefinitely.

  • Event listeners: Listening for events from the browser or other extensions.

  • Communication with other parts of the extension: Sending messages to the content script or the popup.

Example background.js:

chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed!');
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.greeting === 'hello') {
    sendResponse({ farewell: 'goodbye' });
  }
});

3. content.js

The content.js file defines the content script that runs in the context of web pages. It can manipulate the DOM, interact with the page's JavaScript, and communicate with the background script.

Example content.js:

console.log('Content script injected!');

document.addEventListener('click', (event) => {
  console.log('Clicked:', event.target);
  chrome.runtime.sendMessage({ greeting: 'hello' });
});

Interacting Between Components

These components can communicate with each other using the chrome.runtime.sendMessage and chrome.runtime.onMessage APIs. For example, the content script can send a message to the background script, which can then send a response or perform other actions.

Note: Every component has his own context.

Building and Loading Your Extension

To load your extension:

  1. Create a manifest.json file as described earlier.

  2. Place the popup.html, background.js, and content.js files in the same directory as the manifest.json file.

  3. Load the Unpacked Extension:

    • Go to chrome://extensions/ in your Chrome browser.

    • Enable "Developer mode" in the top right corner.

    • Click "Load unpacked" and select the directory containing your extension files.

      Additional Tip: Use chrome.storage for Persistent Data.

    • chrome.storage is a powerful API that allows your Chrome extension to store data persistently. This is useful for storing user preferences, extension state, and other information that needs to be retained across browser sessions.