谷歌浏览器取色器插件源码学习分享

57 阅读2分钟

在使用谷歌浏览器的时候,我们经常会使用到浏览器插件,作为技术肯定也要学习一下浏览器插件的开发咯,这篇文章给大家分享一个 我最近开发的一个浏览器插件-取色器,因为是学习阶段,所以功能做的还是比较简单的。

插件样子

image.png

使用技术:html css和js

image.png

插件部分代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>取色器</title>
  <style>
    body {
      width: 200px;
      padding: 15px;
      font-family: Arial, sans-serif;
      margin: 0;
    }
    h3 {
      margin: 0 0 15px 0;
      text-align: center;
      color: #333;
    }
    #startBtn {
      width: 100%;
      padding: 12px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 16px;
      font-weight: bold;
      transition: transform 0.2s, box-shadow 0.2s;
    }
    #startBtn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    #startBtn:active {
      transform: translateY(0);
    }
    .tip {
      margin-top: 15px;
      font-size: 12px;
      color: #666;
      text-align: center;
      line-height: 1.5;
    }
    .ad {
      margin-top: 20px;
      padding-top: 15px;
      border-top: 1px solid #e0e0e0;
      font-size: 11px;
      color: #999;
      text-align: center;
      line-height: 1.6;
    }
    .ad a {
      color: #667eea;
      text-decoration: none;
    }
    .ad a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <h3>🎨 取色器</h3>
  <button id="startBtn">开始取色</button>
  <div class="tip">
    点击按钮后,在网页上任意位置<br>
    左键点击即可获取颜色值
  </div>
  <div class="ad">
    万物OOP出品<br>
    <a href="https://www.wwwoop.com" target="_blank">www.wwwoop.com</a>
  </div>
  <script src="popup.js"></script>
</body>
</html>
// 获取开始取色按钮
const startBtn = document.getElementById('startBtn');

// 点击开始取色按钮
startBtn.addEventListener('click', async () => {
  // 向当前活动标签页发送消息,开始取色模式
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  if (tab && tab.id) {
    try {
      // 先尝试发送消息
      await chrome.tabs.sendMessage(tab.id, { action: 'startPickColor' });
      window.close();
    } catch (error) {
      // 如果消息发送失败,说明content script未加载,先注入
      console.log('Content script未加载,正在注入...');
      try {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          files: ['content.js']
        });
        // 注入CSS
        await chrome.scripting.insertCSS({
          target: { tabId: tab.id },
          files: ['content.css']
        });
        // 重新发送消息
        await chrome.tabs.sendMessage(tab.id, { action: 'startPickColor' });
        window.close();
      } catch (injectError) {
        console.error('注入脚本失败:', injectError);
        alert('无法在此页面使用取色器,请刷新页面后重试');
      }
    }
  }
});