Chapter 01 Chrome Extension Basics

Haiyue
11min

Chapter 1: Chrome Extension Basics

Learning Objectives
  1. Understand the basic concepts and working principles of Chrome Extensions
  2. Understand the composition structure and core files of extensions
  3. Master the Chrome Web Store publishing process

Knowledge Summary

Chrome Extension Basic Concepts

Chrome Extension is a small software program that can modify and enhance the functionality of the Google Chrome browser. Extensions are built using standard web technologies: HTML, CSS, and JavaScript.

Extension Characteristics
  • Lightweight: Extensions are small in size with focused functionality
  • Modular: Components are independent and communicate through message passing
  • Secure: Run in a sandboxed environment with restricted permissions
  • Cross-platform: Can run on all platforms that support Chrome

How Extensions Work

🔄 正在渲染 Mermaid 图表...

Core Components of Extensions

ComponentPurposeRuntime EnvironmentRequired
manifest.jsonConfiguration file declaring extension information-Required
Background ScriptBackend logic processingExtension processOptional
Content ScriptWeb page content interactionWeb page contextOptional
PopupInterface shown when clicking iconIndependent windowOptional
OptionsSettings pageIndependent pageOptional
IconsExtension icons-Recommended

Creating Your First Extension

Basic Directory Structure

Example extension basic directory structure:

MyFirstExtension/
├── manifest.json      # Required: Extension configuration file
├── popup.html         # Popup page
├── popup.js           # Popup page script
├── images/            # Icons directory
│   ├── icon-16.png
│   ├── icon-48.png
│   └── icon-128.png
├── scripts/           # Scripts directory
│   ├── background.js  # Background script
│   └── content.js     # Content script
└── styles/            # Styles directory
    └── popup.css
// manifest.json - Extension configuration file example
{
  "manifest_version": 3,  // Use the latest Manifest V3
  "name": "MyFirstExtension",
  "version": "1.0.0",
  "description": "My first Chrome extension",
  "icons": {
    "16": "images/icon-16.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon-16.png",
      "48": "images/icon-48.png",
      "128": "images/icon-128.png"
    }
  },
  "permissions": []  // Add permissions as needed
}

Hello World Extension Example

Complete Hello World Extension Example

// manifest.json
{
  "manifest_version": 3,
  "name": "Hello World Extension",
  "version": "1.0",
  "description": "A simple Hello World extension",
  "action": {
    "default_popup": "popup.html",
    "default_title": "Click to view Hello World"
  },
  "permissions": ["activeTab", "scripting"]  // Get current tab and script execution permissions
}
<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body {
      width: 200px;
      padding: 10px;
      font-family: Arial, sans-serif;
    }
    h1 {
      color: #4CAF50;
      font-size: 18px;
    }
    button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 8px 16px;
      cursor: pointer;
      border-radius: 4px;
      width: 100%;
      margin-top: 10px;
    }
    button:hover {
      background-color: #45a049;
    }
  </style>
</head>
<body>
  <h1>Hello World!</h1>
  <p id="message">Welcome to Chrome Extensions</p>
  <button id="changeColor">Change Page Background Color</button>
  <script src="popup.js"></script>
</body>
</html>
// popup.js - Popup page script
document.addEventListener('DOMContentLoaded', function() {
  // Get button element
  const button = document.getElementById('changeColor');
  const message = document.getElementById('message');

  // Add click event listener
  button.addEventListener('click', async () => {
    // Get current active tab
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true
    });

    // Execute script in current tab
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: changeBackgroundColor,
    });

    // Update message
    message.textContent = 'Background color changed!';
  });
});

// This function will execute in the web page context
function changeBackgroundColor() {
  // Generate random color
  const colors = ['#FFE4B5', '#E6F3FF', '#F0FFF0', '#FFF0F5', '#F5F5DC'];
  const randomColor = colors[Math.floor(Math.random() * colors.length)];
  document.body.style.backgroundColor = randomColor;
}

Installing and Debugging Extensions

Loading Development Extensions

Developer Mode

Before loading unpublished extensions, you need to enable Chrome’s developer mode

Steps to Load Extension:

  1. Open Chrome browser
  2. Visit chrome://extensions/
  3. Enable “Developer mode” in the top right corner
  4. Click “Load unpacked”
  5. Select the extension directory

Debugging Command Reference:

OperationMethod
View Service Workerchrome://extensions/ → Click “Service Worker” link
View PopupRight-click extension icon → Inspect popup
View Content ScriptF12 to open DevTools → Sources → Content Scripts
Reload Extensionchrome://extensions/ → Click refresh button
// Common debugging commands in developer console

// View stored data
chrome.storage.local.get(null, (data) => {
  console.log('Local Storage:', data);
});

// Clear stored data
chrome.storage.local.clear(() => {
  console.log('Storage cleared');
});

// View all permissions
chrome.permissions.getAll((permissions) => {
  console.log('Permissions:', permissions);
});

// Verify manifest.json required fields
const requiredFields = ['manifest_version', 'name', 'version'];
// manifest_version must be 2 or 3

Chrome Web Store Publishing Process

Pre-Publishing Checklist

Pre-Publishing Checklist:

StatusRequiredTask
RequiredComplete feature development and testing
RequiredPrepare extension icons (128x128, 48x48, 16x16)
RequiredCreate store listing icon (440x280)
RequiredPrepare at least 1 screenshot (1280x800 or 640x400)
RequiredWrite detailed extension description
RequiredSet appropriate permissions (principle of least privilege)
OptionalCreate privacy policy (if collecting user data)
RequiredPrepare $5 USD developer registration fee
RequiredCompress extension as .zip file
OptionalTest compatibility with different Chrome versions

Store Listing Information Structure:

// Required information for store listing
const storeAssets = {
  name: "My Awesome Extension",
  shortDescription: "",      // Maximum 132 characters
  detailedDescription: "",   // Maximum 16,000 characters
  category: "",              // e.g.: Productivity, Entertainment, Social, etc.
  language: "zh-CN",
  screenshots: [],           // At least 1, maximum 5
  promotionalImages: {
    smallTile: "440x280.png",   // Small promotional tile (required)
    largeTile: "920x680.png",   // Large promotional tile (optional)
    marquee: "1400x560.png"     // Marquee promotional banner (optional)
  },
  supportUrl: "",            // Support website or email
  privacyPolicyUrl: ""       // Privacy policy link
};

Publishing Guide

Publishing Process Overview
  1. Register Developer Account → Pay $5 registration fee
  2. Prepare Publishing Assets → Icons, screenshots, description
  3. Upload Extension Package → Submit .zip file
  4. Fill Store Information → Complete listing details
  5. Submit for Review → Wait for Google review
  6. Publish Live → Go live after review approval

Detailed Publishing Steps:

Step 1: Register Developer Account

  1. Visit https://chrome.google.com/webstore/devconsole
  2. Login with Google account
  3. Pay $5 USD one-time registration fee
  4. Fill in developer information

Step 2: Upload Extension Package

  • File size: Maximum 100MB
  • File format: .zip
  • Do not include node_modules or other development files

Step 3: Submit for Review Review criteria:

  • Functionality testing
  • Security checks
  • Policy compliance
  • User experience

Estimated review time: 1-3 business days

Review Status Descriptions:

StatusDescription
pendingWaiting for submission
under_reviewUnder review
approvedReview approved, ready to publish
rejectedReview rejected, needs modification

Common Rejection Reasons:

  • Excessive permission requests
  • Inaccurate functionality description
  • Contains malicious code
  • Violates content policy
Post-Publishing Maintenance
  • Version Updates: Update version number when fixing bugs or adding features
  • User Feedback: Respond promptly to user comments and issues
  • Data Analysis: Monitor downloads, active users, and other metrics
  • Policy Updates: Pay attention to Chrome policy changes and adjust accordingly

Chapter Summary

This chapter introduced the basics of Chrome Extensions, including:

  1. Basic Concepts: Learned the definition, characteristics, and working principles of extensions
  2. Core Components: Studied the roles of manifest.json and various scripts
  3. Development Process: Created the first Hello World extension
  4. Debugging Methods: Mastered methods for loading and debugging extensions
  5. Publishing Process: Understood the complete process of publishing to Chrome Web Store

The next chapter will dive into setting up the development environment and using tools.

Categories