Chrome扩展开发:如何获取页面背景色并同步至其他窗口?
嘿,这个需求实现起来不算复杂,我来给你一步步讲清楚怎么用纯JS(不用jQuery)做一个Chrome扩展来完成这个功能~
实现步骤拆解
1. 先搞定扩展的核心配置文件 manifest.json
这是Chrome扩展的必备配置,我们需要声明权限和扩展的基本信息:
{ "manifest_version": 3, "name": "背景色同步工具", "version": "1.0", "description": "获取当前页面背景色并同步到指定窗口", "permissions": ["activeTab", "scripting"], "action": { "default_popup": "popup.html", "default_icon": { "16": "icon16.png", "48": "icon48.png" } } }
注:图标可以随便找两张PNG图凑数,暂时忽略也不影响功能测试
2. 编写注入页面的脚本 content.js
这个脚本会被注入到当前网页中,用来精准获取页面的实际背景色(考虑到body可能透明的情况,会 fallback 到html元素的背景):
// 获取页面计算后的真实背景色 function getPageBackgroundColor() { const bodyStyle = window.getComputedStyle(document.body); let bgColor = bodyStyle.backgroundColor; // 如果body背景是全透明,就取html元素的背景 if (bgColor === 'rgba(0, 0, 0, 0)') { const htmlStyle = window.getComputedStyle(document.documentElement); bgColor = htmlStyle.backgroundColor; } return bgColor; } // 把获取到的颜色发送给扩展弹窗 chrome.runtime.sendMessage({type: 'pageBgColor', color: getPageBackgroundColor()});
3. 扩展弹窗的界面与逻辑
先写popup.html,做一个极简的交互界面:
<!DOCTYPE html> <html> <head> <style> body { width: 220px; padding: 15px; margin: 0; font-family: sans-serif; } #getColorBtn { width: 100%; padding: 10px; cursor: pointer; background: #4285f4; color: white; border: none; border-radius: 4px; } #colorPreviewWindow { margin-top: 15px; width: 100%; height: 100px; border: 1px solid #ddd; border-radius: 4px; display: flex; justify-content: center; align-items: center; font-size: 12px; } </style> </head> <body> <button id="getColorBtn">获取当前页面背景色</button> <div id="colorPreviewWindow">点击上方按钮获取颜色</div> <script src="popup.js"></script> </body> </html>
再写popup.js,处理按钮点击、接收页面颜色并修改弹窗内的预览窗口背景:
document.getElementById('getColorBtn').addEventListener('click', async () => { try { // 获取当前激活的标签页 const [activeTab] = await chrome.tabs.query({active: true, currentWindow: true}); // 向当前标签页注入content.js脚本 await chrome.scripting.executeScript({ target: {tabId: activeTab.id}, files: ['content.js'] }); } catch (error) { console.error('获取颜色失败:', error); alert('获取颜色出错啦,请检查页面是否允许脚本运行'); } }); // 接收content.js发来的颜色消息 chrome.runtime.onMessage.addListener((message) => { if (message.type === 'pageBgColor') { const previewWindow = document.getElementById('colorPreviewWindow'); // 修改预览窗口的背景色 previewWindow.style.backgroundColor = message.color; // 设置文字颜色为对比色,避免看不清 previewWindow.style.color = getContrastTextColor(message.color); previewWindow.textContent = `当前背景色:${message.color}`; } }); // 辅助函数:根据背景色生成黑/白对比文字色 function getContrastTextColor(color) { // 处理RGB格式 if (color.startsWith('rgb')) { const [r, g, b] = color.match(/\d+/g).map(Number); const brightness = (r * 299 + g * 587 + b * 114) / 1000; return brightness > 128 ? '#000' : '#fff'; } // 处理十六进制格式(简化版) const hex = color.replace('#', ''); const r = parseInt(hex.slice(0, 2), 16); const g = parseInt(hex.slice(2, 4), 16); const b = parseInt(hex.slice(4, 6), 16); const brightness = (r * 299 + g * 587 + b * 114) / 1000; return brightness > 128 ? '#000' : '#fff'; }
4. 如果要修改的是新浏览器窗口的背景
如果你说的“窗口”是指打开一个全新的浏览器窗口,把popup.js里的消息监听部分改成下面这样就行:
chrome.runtime.onMessage.addListener((message) => { if (message.type === 'pageBgColor') { // 打开新窗口并设置背景色 chrome.windows.create({ url: 'about:blank', width: 450, height: 350 }, (newWindow) => { // 给新窗口的空白页面注入脚本修改背景 chrome.scripting.executeScript({ target: {tabId: newWindow.tabs[0].id}, func: (bgColor) => { document.body.style.backgroundColor = bgColor; }, args: [message.color] }); }); } });
5. 测试扩展
- 打开Chrome浏览器,输入
chrome://extensions/进入扩展管理页 - 开启右上角的「开发者模式」
- 点击「加载已解压的扩展程序」,选择你存放这些文件的文件夹
- 点击浏览器工具栏上的扩展图标,打开弹窗后点击按钮,就能获取当前页面背景色并同步到指定区域/新窗口啦~
内容的提问来源于stack exchange,提问作者Arch
相关产品推荐
相关产品推荐

