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

如何用JavaScript开发Chrome扩展实现网页关键词监控与触发动作

Got it, let's build a straightforward, practical Chrome extension that monitors both page content and your input for specific keywords. We'll use Manifest V3 (the latest standard) since Manifest V2 is being phased out. Here's a step-by-step implementation:

1. Extension Structure

First, create a folder for your extension (e.g., keyword-monitor). Inside it, you'll need two core files:

  • manifest.json: Defines extension permissions and behavior
  • content.js: The script that runs on web pages to scan for keywords

2. Manifest.json Configuration

This sets up the extension to inject our script into all web pages and grants necessary permissions:

{
  "manifest_version": 3,
  "name": "Keyword Monitor",
  "version": "1.0",
  "description": "Scans pages and input for target keywords",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_idle"
    }
  ],
  "permissions": ["activeTab"]
}
  • matches: ["<all_urls>"]: Makes the script run on every web page
  • run_at: "document_idle": Ensures the script loads after the page is mostly ready
  • activeTab: Gives basic access to the current tab (enough for our use case)

3. Content.js Implementation

This script handles scanning existing page content, watching for dynamic content updates, and monitoring user input. We'll keep it simple but effective:

// Define your target keywords here (customize this!)
const TARGET_KEYWORDS = ["urgent", "warning", "discount", "your-custom-keyword"];

// Debounce function to avoid excessive scans (prevents performance hits)
function debounce(func, delay = 500) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

// Core function to scan for keywords and trigger actions
function scanForKeywords() {
  // Scan page content
  const pageText = document.body.textContent.toLowerCase();
  const foundKeywords = TARGET_KEYWORDS.filter(keyword => 
    pageText.includes(keyword.toLowerCase())
  );

  if (foundKeywords.length > 0) {
    // Replace this with your custom action!
    console.log(`Detected keywords: ${foundKeywords.join(", ")}`);
    alert(`Found keywords: ${foundKeywords.join(", ")}`); // Example action
    // You could also highlight elements, send a browser notification, etc.
  }
}

// Monitor user input fields for keywords
function setupInputMonitoring() {
  document.addEventListener("input", (e) => {
    if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") {
      const inputValue = e.target.value.toLowerCase();
      const foundKeywords = TARGET_KEYWORDS.filter(keyword => 
        inputValue.includes(keyword.toLowerCase())
      );

      if (foundKeywords.length > 0) {
        // Custom action for input detection
        console.log(`Keyword detected in input: ${foundKeywords.join(", ")}`);
        e.target.style.border = "2px solid orange"; // Highlight input as example
      } else {
        e.target.style.border = ""; // Reset border if no keyword
      }
    }
  });
}

// Watch for dynamic page updates (e.g., SPA content loads)
function setupDynamicContentMonitoring() {
  const observer = new MutationObserver(debounce(scanForKeywords));
  observer.observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true
  });
}

// Initialize everything when the script loads
document.addEventListener("DOMContentLoaded", () => {
  scanForKeywords(); // Scan initial page content
  setupInputMonitoring(); // Start watching user input
  setupDynamicContentMonitoring(); // Watch for dynamic updates
});

4. Load the Extension into Chrome

  1. Open Chrome and go to chrome://extensions/
  2. Toggle "Developer mode" on (top-right corner)
  3. Click "Load unpacked" and select your extension folder
  4. The extension will now run on every page you visit!

Quick Customization Tips

  • Modify Keywords: Update the TARGET_KEYWORDS array with your own terms
  • Change Actions: Replace the alert() and console logs with whatever you need—like highlighting elements, triggering a browser notification, or sending data to a backend
  • Limit to Specific Sites: Adjust the matches field in manifest.json to target only certain URLs (e.g., ["https://example.com/*"])

This implementation is lightweight, handles dynamic content (like single-page apps), and monitors both page content and user input. It’s easy to tweak to fit your exact needs!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:56:23