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

For*_*rge 4 html javascript google-chrome google-chrome-extension

我正在使用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"
      }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是popup.html

<html>
  <body>
    <input type="button" id="button" style="display:none;">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

script.js

document.body.style.backgroundColor = "yellow";
var button = document.getElementById("button");
button.style.visibility = "visible";
Run Code Online (Sandbox Code Playgroud)

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

Uncaught TypeError: Cannot read property 'style' of null
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能在其中的内容上插入一个按钮http://127.0.0.1:8000(假设我不知道其内容)?

Hai*_* Ai 6

要插入按钮,只需在您的内容脚本中创建按钮并将其插入,就无需(不应)在 popup.html

manifest.json

{
  "manifest_version": 2,
  "name": "my extension",
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"]          
      }
  ]
}
Run Code Online (Sandbox Code Playgroud)

script.js

document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);
Run Code Online (Sandbox Code Playgroud)