第01章 Chrome Extension 基础入门
12/3/25About 8 min
第 1 章:Chrome Extension 基础入门
学习目标
- 了解 Chrome Extension 的基本概念和工作原理
- 理解扩展程序的组成结构和核心文件
- 掌握 Chrome Web Store 的发布流程
知识点总结
Chrome Extension 基本概念
Chrome Extension(Chrome扩展程序)是一种小型软件程序,可以修改和增强 Google Chrome 浏览器的功能。扩展程序使用标准的 Web 技术构建:HTML、CSS 和 JavaScript。
扩展程序的特点
- 轻量级:扩展程序体积小,功能专注
- 模块化:各个组件相互独立,通过消息传递进行通信
- 安全性:运行在沙盒环境中,权限受限
- 跨平台:可在所有支持 Chrome 的平台上运行
扩展程序的工作原理
扩展程序的核心组成
| 组件 | 作用 | 运行环境 | 必需性 |
|---|---|---|---|
| manifest.json | 配置文件,声明扩展信息 | - | 必需 |
| Background Script | 后台逻辑处理 | 扩展进程 | 可选 |
| Content Script | 网页内容交互 | 网页上下文 | 可选 |
| Popup | 点击图标弹出界面 | 独立窗口 | 可选 |
| Options | 设置页面 | 独立页面 | 可选 |
| Icons | 扩展程序图标 | - | 推荐 |
创建第一个扩展程序
基本目录结构
"""
扩展程序基本目录结构示例
"""
import os
import json
def create_extension_structure(extension_name):
"""
创建Chrome扩展的基本目录结构
Args:
extension_name: 扩展程序名称
"""
# 创建基本目录
base_dir = f"./{extension_name}"
os.makedirs(base_dir, exist_ok=True)
os.makedirs(f"{base_dir}/images", exist_ok=True)
os.makedirs(f"{base_dir}/scripts", exist_ok=True)
os.makedirs(f"{base_dir}/styles", exist_ok=True)
# 创建manifest.json
manifest = {
"manifest_version": 3, # 使用最新的Manifest V3
"name": extension_name,
"version": "1.0.0",
"description": "我的第一个Chrome扩展",
"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": [] # 根据需要添加权限
}
# 写入manifest.json
with open(f"{base_dir}/manifest.json", "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
print(f"扩展程序 '{extension_name}' 的基本结构已创建")
return base_dir
# 示例:创建一个名为"MyFirstExtension"的扩展
create_extension_structure("MyFirstExtension")Hello World 扩展示例
"""
创建一个简单的Hello World扩展程序
"""
def create_hello_world_extension():
"""
创建包含完整文件的Hello World扩展
"""
import os
import json
# 创建目录
base_dir = "./HelloWorldExtension"
os.makedirs(base_dir, exist_ok=True)
# 1. manifest.json
manifest_content = {
"manifest_version": 3,
"name": "Hello World Extension",
"version": "1.0",
"description": "一个简单的Hello World扩展",
"action": {
"default_popup": "popup.html",
"default_title": "点击查看Hello World"
},
"permissions": ["activeTab"] # 获取当前标签页权限
}
with open(f"{base_dir}/manifest.json", "w") as f:
json.dump(manifest_content, f, indent=2)
# 2. popup.html
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">欢迎使用Chrome扩展</p>
<button id="changeColor">改变页面背景色</button>
<script src="popup.js"></script>
</body>
</html>"""
with open(f"{base_dir}/popup.html", "w", encoding="utf-8") as f:
f.write(popup_html)
# 3. popup.js
popup_js = """// 当DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 获取按钮元素
const button = document.getElementById('changeColor');
const message = document.getElementById('message');
// 添加点击事件监听器
button.addEventListener('click', async () => {
// 获取当前活动标签页
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true
});
// 在当前标签页中执行脚本
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: changeBackgroundColor,
});
// 更新消息
message.textContent = '背景色已改变!';
});
});
// 这个函数将在网页上下文中执行
function changeBackgroundColor() {
// 生成随机颜色
const colors = ['#FFE4B5', '#E6F3FF', '#F0FFF0', '#FFF0F5', '#F5F5DC'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
document.body.style.backgroundColor = randomColor;
}"""
with open(f"{base_dir}/popup.js", "w", encoding="utf-8") as f:
f.write(popup_js)
print("Hello World 扩展已创建完成!")
print(f"扩展位置: {os.path.abspath(base_dir)}")
return base_dir
# 创建Hello World扩展
create_hello_world_extension()安装和调试扩展程序
加载开发中的扩展
开发者模式
在加载未发布的扩展之前,需要先开启Chrome的开发者模式
"""
模拟Chrome扩展加载和调试流程
"""
class ExtensionDebugger:
"""Chrome扩展调试器类"""
def __init__(self, extension_path):
self.extension_path = extension_path
self.is_loaded = False
self.errors = []
def validate_manifest(self):
"""验证manifest.json文件"""
import json
import os
manifest_path = os.path.join(self.extension_path, "manifest.json")
try:
with open(manifest_path, 'r') as f:
manifest = json.load(f)
# 检查必需字段
required_fields = ["manifest_version", "name", "version"]
for field in required_fields:
if field not in manifest:
self.errors.append(f"缺少必需字段: {field}")
# 检查manifest版本
if manifest.get("manifest_version") not in [2, 3]:
self.errors.append("manifest_version 必须是 2 或 3")
print("✅ Manifest 验证通过" if not self.errors else "❌ Manifest 验证失败")
return len(self.errors) == 0
except FileNotFoundError:
self.errors.append("找不到 manifest.json 文件")
return False
except json.JSONDecodeError as e:
self.errors.append(f"JSON 解析错误: {str(e)}")
return False
def load_extension(self):
"""模拟加载扩展"""
if self.validate_manifest():
self.is_loaded = True
print(f"扩展已加载: {self.extension_path}")
print("加载步骤:")
print("1. 打开 Chrome 浏览器")
print("2. 访问 chrome://extensions/")
print("3. 开启右上角的'开发者模式'")
print("4. 点击'加载已解压的扩展程序'")
print(f"5. 选择目录: {self.extension_path}")
else:
print("加载失败,错误信息:")
for error in self.errors:
print(f" - {error}")
def debug_console_commands(self):
"""调试控制台常用命令"""
commands = {
"查看背景页": "chrome://extensions/ → 点击'背景页'链接",
"查看弹窗页": "右键扩展图标 → 审查弹出内容",
"查看Content Script": "F12打开开发者工具 → Sources → Content Scripts",
"查看存储数据": "chrome.storage.local.get(null, console.log)",
"清除存储数据": "chrome.storage.local.clear()",
"重新加载扩展": "chrome://extensions/ → 点击刷新按钮",
"查看权限": "chrome.permissions.getAll(console.log)"
}
print("\n🔧 调试命令参考:")
for desc, cmd in commands.items():
print(f" {desc}:")
print(f" {cmd}")
# 使用示例
debugger = ExtensionDebugger("./HelloWorldExtension")
debugger.load_extension()
debugger.debug_console_commands()Chrome Web Store 发布流程
发布准备清单
"""
Chrome扩展发布前的准备工作
"""
class PublishPreparation:
"""发布准备类"""
def __init__(self):
self.checklist = []
self.store_assets = {}
def create_checklist(self):
"""创建发布检查清单"""
self.checklist = [
{"task": "完成功能开发和测试", "required": True, "done": False},
{"task": "准备扩展图标 (128x128, 48x48, 16x16)", "required": True, "done": False},
{"task": "创建商店列表图标 (440x280)", "required": True, "done": False},
{"task": "准备至少1张截图 (1280x800 或 640x400)", "required": True, "done": False},
{"task": "编写详细的扩展描述", "required": True, "done": False},
{"task": "设置适当的权限(最小权限原则)", "required": True, "done": False},
{"task": "创建隐私政策(如果收集用户数据)", "required": False, "done": False},
{"task": "准备$5美元的开发者注册费", "required": True, "done": False},
{"task": "压缩扩展为.zip文件", "required": True, "done": False},
{"task": "测试不同Chrome版本兼容性", "required": False, "done": False}
]
return self.checklist
def prepare_store_listing(self, extension_name):
"""准备商店列表信息"""
self.store_assets = {
"name": extension_name,
"short_description": "", # 最多132个字符
"detailed_description": "", # 最多16,000个字符
"category": "", # 如:生产力工具、娱乐、社交等
"language": "zh-CN",
"screenshots": [], # 至少1张,最多5张
"promotional_images": {
"small_tile": "440x280.png", # 小型推广图块
"large_tile": "920x680.png", # 大型推广图块(可选)
"marquee": "1400x560.png" # 横幅推广图(可选)
},
"support_url": "", # 支持网站或邮箱
"privacy_policy_url": "" # 隐私政策链接
}
return self.store_assets
def create_zip_package(self, source_dir, output_file="extension.zip"):
"""创建扩展的ZIP包"""
import zipfile
import os
print(f"正在打包扩展: {source_dir}")
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, source_dir)
# 排除不需要的文件
if not file.startswith('.') and not file.endswith('.zip'):
zipf.write(file_path, arcname)
print(f" 添加: {arcname}")
print(f"✅ 打包完成: {output_file}")
return output_file
# 使用示例
prep = PublishPreparation()
checklist = prep.create_checklist()
print("📋 发布前检查清单:")
for item in checklist:
status = "✅" if item["done"] else "⬜"
required = "必需" if item["required"] else "可选"
print(f"{status} [{required}] {item['task']}")
# 准备商店列表
store_info = prep.prepare_store_listing("My Awesome Extension")
print("\n📦 商店列表信息结构:")
for key, value in store_info.items():
print(f" - {key}: {type(value).__name__}")发布步骤指南
发布流程概览
- 注册开发者账号 → 支付$5注册费
- 准备发布资源 → 图标、截图、描述
- 上传扩展包 → 提交.zip文件
- 填写商店信息 → 完善列表信息
- 提交审核 → 等待Google审核
- 发布上线 → 审核通过后上线
"""
模拟Chrome Web Store发布流程
"""
class ChromeWebStorePublisher:
"""Chrome Web Store 发布器"""
def __init__(self):
self.developer_registered = False
self.extension_uploaded = False
self.review_status = "pending"
def register_developer(self, email):
"""注册开发者账号"""
print(f"📝 注册开发者账号: {email}")
print("步骤:")
print("1. 访问 https://chrome.google.com/webstore/devconsole")
print("2. 使用Google账号登录")
print("3. 支付$5美元一次性注册费")
print("4. 填写开发者信息")
self.developer_registered = True
return {
"status": "registered",
"developer_id": "dev_" + email.split('@')[0],
"registration_fee": "$5.00"
}
def upload_extension(self, zip_file):
"""上传扩展包"""
if not self.developer_registered:
print("❌ 请先注册开发者账号")
return False
print(f"📤 上传扩展包: {zip_file}")
print("上传限制:")
print(" - 文件大小: 最大 100MB")
print(" - 文件格式: .zip")
print(" - 不包含node_modules等开发文件")
self.extension_uploaded = True
return {"status": "uploaded", "file": zip_file}
def submit_for_review(self):
"""提交审核"""
if not self.extension_uploaded:
print("❌ 请先上传扩展包")
return False
print("🔍 提交审核")
print("审核要点:")
print(" - 功能性测试")
print(" - 安全性检查")
print(" - 政策合规性")
print(" - 用户体验")
print("\n预计审核时间: 1-3个工作日")
self.review_status = "under_review"
return {"status": "submitted", "estimated_time": "1-3 days"}
def check_review_status(self):
"""检查审核状态"""
status_messages = {
"pending": "等待提交",
"under_review": "审核中...",
"approved": "✅ 审核通过,可以发布",
"rejected": "❌ 审核未通过,需要修改"
}
print(f"当前状态: {status_messages[self.review_status]}")
if self.review_status == "rejected":
print("常见拒绝原因:")
print(" - 权限过度申请")
print(" - 功能描述不准确")
print(" - 包含恶意代码")
print(" - 违反内容政策")
return self.review_status
# 使用示例
publisher = ChromeWebStorePublisher()
# 步骤1: 注册开发者
dev_info = publisher.register_developer("developer@example.com")
print(f"\n开发者信息: {dev_info}\n")
# 步骤2: 上传扩展
upload_result = publisher.upload_extension("extension.zip")
print(f"\n上传结果: {upload_result}\n")
# 步骤3: 提交审核
review_result = publisher.submit_for_review()
print(f"\n审核信息: {review_result}\n")
# 步骤4: 检查状态
publisher.check_review_status()发布后的维护
- 版本更新: 修复bug、添加功能时需要更新版本号
- 用户反馈: 及时回复用户评论和问题
- 数据分析: 关注下载量、活跃用户等数据
- 政策更新: 关注Chrome政策变化,及时调整
本章小结
本章介绍了Chrome Extension的基础知识,包括:
- 基本概念: 了解了扩展程序的定义、特点和工作原理
- 核心组件: 学习了manifest.json、各类脚本的作用
- 开发流程: 创建了第一个Hello World扩展
- 调试方法: 掌握了加载和调试扩展的方法
- 发布流程: 了解了发布到Chrome Web Store的完整流程
下一章将深入学习开发环境的搭建和工具的使用。
