Lesson 02-Setting Up the Development Environment

Development Environment Preparation

1. Choosing Development Tools

  • Visual Studio Code: A lightweight yet powerful source-code editor that supports numerous plugins, ideal for browser extension development.
  • Chrome DevTools: Built into the Chrome browser, providing robust debugging and testing tools.

2. Installing Necessary Software

  • Node.js: While not mandatory, using npm or yarn to manage project dependencies and automate tasks simplifies development.
  • Git: Used for version control to manage code changes.

3. Creating a Project Directory

Create a new directory on your local drive to store your browser extension project.

mkdir my_extension_project
cd my_extension_project
Bash

Project Initialization

1. Initializing a Git Repository

git init
Bash

2. Initializing an npm Project

npm init -y
Bash

This will create a package.json file to record project metadata and dependencies.

Project Structure Setup

A basic browser extension project structure might look like this:

my_extension_project/
├── src/
│   ├── background.js
│   ├── content.js
│   └── popup.html
├── images/
│   ├── icon16.png
│   ├── icon48.png
│   └── icon128.png
├── manifest.json
└── .gitignore
Bash
  • src/: Contains all source code files.
  • images/: Stores image resources required by the extension, such as icons.
  • manifest.json: The core configuration file for the extension.
  • .gitignore: Specifies which files or directories Git should ignore.

Writing Code

1. Creating manifest.json

This is the extension’s configuration file, defining basic information, permissions, and script entry points.

{
  "manifest_version": 3,
  "name": "My First Extension",
  "version": "1.0",
  "description": "A simple extension that changes the background color of a webpage.",
  "permissions": ["activeTab"],
  "background": {
    "service_worker": "src/background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["src/content.js"]
    }
  ],
  "action": {
    "default_popup": "src/popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  }
}
JavaScript

2. Writing the Background Script background.js

// src/background.js
chrome.action.onClicked.addListener((tab) => {
  chrome.tabs.sendMessage(tab.id, { action: 'changeColor' });
});
JavaScript

3. Writing the Content Script content.js

// src/content.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'changeColor') {
    document.body.style.backgroundColor = '#ff0';
  }
});
JavaScript

4. Creating the Popup popup.html

<!-- src/popup.html -->
<!DOCTYPE html>
<html>
<head>
  <title>My Extension Popup</title>
</head>
<body>
  <button id="changeColorButton">Change Background Color</button>
  <script src="popup.js"></script>
</body>
</html>
HTML

5. Writing the Popup Script popup.js

// src/popup.js
document.getElementById('changeColorButton').addEventListener('click', () => {
  chrome.runtime.sendMessage({ action: 'changeColor' });
});
JavaScript

Loading and Testing the Extension

1. Open Chrome Extension Management Page
Enter chrome://extensions in the Chrome browser and press Enter.

2. Enable Developer Mode
Check “Developer mode” in the top-right corner of the page.

3. Load Unpacked Extension
Click “Load unpacked” and select your project directory.

4. Test the Extension
Locate your extension icon in the browser toolbar, click it, and test whether its functionality works as expected.

Debugging and Optimization

Use Chrome DevTools to debug your extension code. Open DevTools in the extension’s popup or content scripts, check console output, set breakpoints, and inspect variable changes to identify and fix issues.

Modularization and Code Organization

As the extension’s functionality grows, so does the codebase, making modular programming increasingly important. Using the ES6 module system, you can split code into multiple files, with each file handling a specific function, and import them in the main file.

For example, you can encapsulate network request-related functionality in a module:

// src/network.js
export const fetchData = async (url) => {
  const response = await fetch(url);
  return response.json();
};
JavaScript

Then import and use it in other files:

// src/background.js
import { fetchData } from './network.js';

chrome.action.onClicked.addListener(async (tab) => {
  const data = await fetchData('https://api.example.com/data');
  console.log(data);
});
JavaScript

State Management and Storage

Browser extensions may need to share data across pages or retain state after the browser is closed. While localStorage or sessionStorage can be used, Chrome’s storage API is recommended for finer control and better cross-browser compatibility.

// Set data
chrome.storage.sync.set({ key: 'value' }, () => {
  console.log('Data saved.');
});

// Get data
chrome.storage.sync.get(['key'], (result) => {
  console.log(result.key);
});
JavaScript

Internationalization and Multi-Language Support

Use i18n (internationalization) and l10n (localization) to support multiple languages, enabling your extension to reach a global audience.

// manifest.json
{
  "default_locale": "en",
  "_locales": {
    "en": {
      "messages": {
        "extensionName": {
          "message": "My Extension"
        }
      }
    },
    "es": {
      "messages": {
        "extensionName": {
          "message": "Mi Extensión"
        }
      }
    }
  }
}
JavaScript
Share your love