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

Chrome扩展Content Script无法注入Twitter页面的解决方案咨询

Chrome扩展Manifest V3下Content Script无法注入Twitter页面的解决方法

现有配置与代码

manifest.json

{
   "name": "React Extension",
   "description": "Chrome Extension in React!",
   "version": "1.0.0",
   "manifest_version": 3,
   "icons": {
      "16": "icon.png",
      "48": "icon.png",
      "128": "icon.png"
   },
   "action": {
      "default_popup": "popup.html",
      "default_title": "React Extension",
      "default_icon": "icon.png"
   },
   "permissions": ["storage"],
   "options_page": "options.html",
   "background": {
      "service_worker": "background.js"
   },
   "content_scripts": [
      {
         "matches": ["https://twitter.com/*"],
         "js": ["contentScript.js"],
         "run_at": "document_idle"
      }
   ]
}

contentScript.js

document.addEventListener('DOMContentLoaded', function() {
     // Your JavaScript function goes here
     loadForm();
});

function loadForm() {    
      const target = document.querySelector("input[placeholder='Search']");

      if (target) {
          // Create a new input element
          const newInput = document.createElement("input");
          newInput.type = "text"; // Set the input type as text    
          newInput.placeholder = "Check if tweet is news";
          // Insert the new input element after the existing element
          // If target is the last child, this will insert it at the end
          target.parentNode.insertBefore(newInput, target.nextSibling);
      }
}

问题原因

Twitter是单页应用(SPA),页面内容通过JavaScript动态渲染,DOMContentLoaded只会在初始页面加载时触发一次,后续切换页面或加载新内容时不会再触发。另外,你使用的input[placeholder='Search']选择器可能不准确——Twitter的搜索框实际可能使用了更稳定的属性(比如data-testid),或者元素在DOMContentLoaded触发时还未完全渲染。

可行解决方案

1. 用MutationObserver监听DOM变化

针对SPA动态加载的特性,通过监听DOM树的变化,在目标元素出现时执行插入操作:

修改contentScript.js:

function loadForm() {    
  // 改用Twitter搜索框的稳定测试ID选择器
  const target = document.querySelector("input[data-testid='SearchBox_input']"); 
  if (target) {
    const newInput = document.createElement("input");
    newInput.type = "text";
    newInput.placeholder = "Check if tweet is news";
    target.parentNode.insertBefore(newInput, target.nextSibling);
    return true; // 找到元素后停止监听
  }
  return false;
}

// 初始尝试加载
if (!loadForm()) {
  // 监听DOM变化,直到目标元素出现
  const observer = new MutationObserver((mutations) => {
    if (loadForm()) {
      observer.disconnect(); // 完成后停止监听
    }
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
}

2. 修正目标元素选择器

打开Twitter页面,右键搜索框选择「检查」,查看实际的元素属性。当前Twitter的搜索框通常带有data-testid="SearchBox_input"属性,用这个选择器比placeholder更可靠(placeholder可能因语言切换变化)。

3. 调整content script的运行时机

在manifest.json中,将run_at改为document_end,确保DOM基本构建完成后再注入:

"content_scripts": [
  {
    "matches": ["https://twitter.com/*"],
    "js": ["contentScript.js"],
    "run_at": "document_end"
  }
]

4. 手动触发注入测试

如果自动注入仍有问题,可以通过chrome.scripting.executeScript手动触发注入,比如在popup中添加按钮触发:

首先在manifest.json中添加权限:

"permissions": ["storage", "scripting"],
"host_permissions": ["https://twitter.com/*"]

然后在popup.js中添加代码:

document.getElementById('injectBtn').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
  await chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['contentScript.js']
  });
});

5. 检查扩展状态

  • 打开chrome://extensions/,确保你的扩展已启用,没有报错。
  • 查看扩展的「检查视图」→「控制台」,排查是否有加载错误或DOM选择器相关的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:55:30