实现一个谷歌插件js
创建谷歌插件的基本结构
谷歌插件(Chrome Extension)通常由多个文件组成,包括manifest.json配置文件、背景脚本(background script)、内容脚本(content script)和前端页面(popup或options页面)。
manifest.json是必须的配置文件,示例结构如下:
{
"manifest_version": 3,
"name": "示例插件",
"version": "1.0",
"description": "这是一个简单的Chrome插件示例",
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"permissions": ["activeTab", "storage"]
}
添加背景脚本
背景脚本在插件生命周期中长期运行,处理事件和全局状态。创建一个background.js文件:
chrome.runtime.onInstalled.addListener(() => {
console.log('插件已安装');
});
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ['content.js']
});
});
创建内容脚本
内容脚本可以访问和操作网页DOM。创建content.js文件:

// 修改页面背景色
document.body.style.backgroundColor = 'lightblue';
// 向页面注入自定义元素
const div = document.createElement('div');
div.textContent = '这是由插件添加的内容';
document.body.appendChild(div);
实现弹出页面
创建popup.html作为插件的弹出界面:
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 200px; padding: 10px; }
button { margin-top: 10px; }
</style>
</head>
<body>
<h3>插件控制面板</h3>
<button id="changeColor">改变页面颜色</button>
<script src="popup.js"></script>
</body>
</html>
创建对应的popup.js处理交互:

document.getElementById('changeColor').addEventListener('click', () => {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.scripting.executeScript({
target: {tabId: tabs[0].id},
function: changePageColor
});
});
});
function changePageColor() {
document.body.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
}
使用存储功能
在manifest.json中添加storage权限后,可以使用chrome.storage API保存数据:
// 保存数据
chrome.storage.local.set({key: value}, () => {
console.log('数据已保存');
});
// 读取数据
chrome.storage.local.get(['key'], (result) => {
console.log('读取数据:', result.key);
});
调试和测试插件
在Chrome浏览器地址栏输入chrome://extensions/,启用开发者模式,点击"加载已解压的扩展程序"选择插件目录。使用Chrome开发者工具(Ctrl+Shift+I)可以调试背景脚本和内容脚本。
发布插件
完成开发后,可以打包插件为.crx文件并通过Chrome网上应用店发布。需要注册开发者账号并支付一次性费用。
以上代码示例展示了谷歌插件开发的基本流程和常用API。实际开发中可以根据需求组合使用不同的API和功能模块。






