Chapter 01 Chrome Extension Basics
Chapter 1: Chrome Extension Basics
- Understand the basic concepts and working principles of Chrome Extensions
- Understand the composition structure and core files of extensions
- 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.
- 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
Core Components of Extensions
| Component | Purpose | Runtime Environment | Required |
|---|---|---|---|
| manifest.json | Configuration file declaring extension information | - | Required |
| Background Script | Backend logic processing | Extension process | Optional |
| Content Script | Web page content interaction | Web page context | Optional |
| Popup | Interface shown when clicking icon | Independent window | Optional |
| Options | Settings page | Independent page | Optional |
| Icons | Extension 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
Before loading unpublished extensions, you need to enable Chrome’s developer mode
Steps to Load Extension:
- Open Chrome browser
- Visit
chrome://extensions/ - Enable “Developer mode” in the top right corner
- Click “Load unpacked”
- Select the extension directory
Debugging Command Reference:
| Operation | Method |
|---|---|
| View Service Worker | chrome://extensions/ → Click “Service Worker” link |
| View Popup | Right-click extension icon → Inspect popup |
| View Content Script | F12 to open DevTools → Sources → Content Scripts |
| Reload Extension | chrome://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:
| Status | Required | Task |
|---|---|---|
| ⬜ | Required | Complete feature development and testing |
| ⬜ | Required | Prepare extension icons (128x128, 48x48, 16x16) |
| ⬜ | Required | Create store listing icon (440x280) |
| ⬜ | Required | Prepare at least 1 screenshot (1280x800 or 640x400) |
| ⬜ | Required | Write detailed extension description |
| ⬜ | Required | Set appropriate permissions (principle of least privilege) |
| ⬜ | Optional | Create privacy policy (if collecting user data) |
| ⬜ | Required | Prepare $5 USD developer registration fee |
| ⬜ | Required | Compress extension as .zip file |
| ⬜ | Optional | Test 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
- Register Developer Account → Pay $5 registration fee
- Prepare Publishing Assets → Icons, screenshots, description
- Upload Extension Package → Submit .zip file
- Fill Store Information → Complete listing details
- Submit for Review → Wait for Google review
- Publish Live → Go live after review approval
Detailed Publishing Steps:
Step 1: Register Developer Account
- Visit https://chrome.google.com/webstore/devconsole
- Login with Google account
- Pay $5 USD one-time registration fee
- 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:
| Status | Description |
|---|---|
| pending | Waiting for submission |
| under_review | Under review |
| approved | Review approved, ready to publish |
| rejected | Review rejected, needs modification |
Common Rejection Reasons:
- Excessive permission requests
- Inaccurate functionality description
- Contains malicious code
- Violates content policy
- 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:
- Basic Concepts: Learned the definition, characteristics, and working principles of extensions
- Core Components: Studied the roles of manifest.json and various scripts
- Development Process: Created the first Hello World extension
- Debugging Methods: Mastered methods for loading and debugging extensions
- 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.