如何使用 Chrome 扩展程序向网页注入按钮

How to inject a button to a webpage with Chrome Extension

本文关键字:网页 注入 按钮 程序 何使用 Chrome 扩展      更新时间:2023-09-26

我正在使用content scripts,我想向网页注入一个按钮。

这是我manifest.json

{
  "manifest_version": 2,
  "name": "my extension",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:8000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]
}

这是popup.html

<html>
  <body>
    <input type="button" id="button" style="display:none;">
  </body>
</html>

script.js

document.body.style.backgroundColor = "yellow";
var button = document.getElementById("button");
button.style.visibility = "visible";

转到http://127.0.0.1:8000时,我看到背景变为黄色,但是它找不到按钮,因为它不是我的本地服务器提供的网页的一部分。它显示此错误:

Uncaught TypeError: Cannot read property 'style' of null

我应该怎么做才能在http://127.0.0.1:8000的内容顶部注入一个按钮(假设我不知道它的内容)?

要插入按钮,只需在内容脚本中创建它并插入它,您不需要(不应该)在popup.html中声明它

manifest.json

{
  "manifest_version": 2,
  "name": "my extension",
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"]          
      }
  ]
}

脚本.js

document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);

您应该在content_scripts属性中添加"run_at": "document_end"

document_end中,脚本文件将在DOM完成后注入。这样,document将能够找到您丢失的按钮:)

"content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]