You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展开发:实现页面元素点击及弹窗展示点击次数需求

Solution for Adding Click Count Display to Your Chrome Extension

Let's fix up your extension to track and display the number of times you've clicked that non-defective button. Here's a step-by-step breakdown of the changes you need to make:

1. Update manifest.json

First, we need to add the storage permission (to save the click count) and properly declare your content script (instead of auto-running it):

{
  "manifest_version": 2,
  "name": "Dig Dug",
  "description": "Label Non-Defective Counts",
  "version": "1.0",
  "permissions": ["tabs", "<all_urls>", "storage"],
  "browser_action": {
    "default_icon": {
      "19": "icons/19.png",
      "38": "icons/38.png"
    },
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "icons/16.png",
    "19": "icons/19.png",
    "38": "icons/38.png",
    "64": "icons/64.png",
    "128": "icons/128.png"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

2. Fix and Update content.js

Rename your existing content script code to content.js and adjust it to listen for messages from the popup (instead of auto-executing). I also fixed a couple of bugs in your original click logic:

// content.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // Only respond to the "clickNonDefective" action
  if (request.action === "clickNonDefective") {
    try {
      const submitButton = document.getElementById("submit-non-defective-button");
      if (submitButton) {
        submitButton.click();
        sendResponse({ success: true });
      } else {
        sendResponse({ success: false, error: "Submit button not found on page" });
      }
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }
});

3. Create popup.html

This is the UI for your extension's popup, which will display the click count:

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      width: 220px;
      padding: 1rem;
      font-family: system-ui, -apple-system, sans-serif;
      margin: 0;
    }
    .count-container {
      margin-top: 1rem;
      text-align: center;
    }
    #clickCount {
      font-size: 1.5rem;
      font-weight: bold;
      color: #2ecc71;
    }
  </style>
</head>
<body>
  <h3>Dig Dug</h3>
  <p>Non-defective submissions:</p>
  <div class="count-container">
    <span id="clickCount">0</span>
  </div>
  <script src="popup.js"></script>
</body>
</html>

4. Add popup.js

This script handles the popup logic: it triggers the button click on the current page, updates the click count in storage, and displays the count in the popup:

// popup.js
document.addEventListener('DOMContentLoaded', async () => {
  const countDisplay = document.getElementById('clickCount');

  // Get the saved click count from storage (default to 0 if none exists)
  let { clickCount = 0 } = await chrome.storage.local.get('clickCount');

  // Get the active tab to send a message to its content script
  const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

  try {
    // Send a message to the content script to trigger the button click
    const response = await chrome.tabs.sendMessage(activeTab.id, { action: "clickNonDefective" });
    
    if (response.success) {
      // Increment count and save it back to storage
      clickCount++;
      await chrome.storage.local.set({ clickCount });
    } else {
      console.error('Failed to click button:', response.error);
    }
  } catch (err) {
    console.error('Error communicating with content script:', err);
  }

  // Update the popup with the latest count
  countDisplay.textContent = clickCount;
});

How It Works

  • Storage: We use chrome.storage.local to persist the click count across browser sessions.
  • Message Passing: The popup sends a message to the content script in the active tab to trigger the button click, ensuring the action only happens when you click the extension icon.
  • Error Handling: We added basic error handling to catch cases where the button isn't found or communication fails.

Just replace your existing files with these, and your extension will now track and display the number of non-defective submissions every time you click the icon!

内容的提问来源于stack exchange,提问作者Tirumal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:32:22