Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在带有Chrome扩展的网页中插入按钮_Javascript_Html_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript 如何在带有Chrome扩展的网页中插入按钮

Javascript 如何在带有Chrome扩展的网页中插入按钮,javascript,html,google-chrome,google-chrome-extension,Javascript,Html,Google Chrome,Google Chrome Extension,我正在使用,我想在网页中插入一个按钮 这是我的manifest.json: { "manifest_version": 2, "name": "my extension", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": [ "activeTab" ], "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>
当转到
http://127.0.0.1:8000
我看到背景变为黄色,但它没有“查找”按钮,因为它不是本地服务器提供服务的网页的一部分。它显示了这个错误:

Uncaught TypeError: Cannot read property 'style' of null
http://127.0.0.1:8000
(假设我不知道它的内容)

您应该在
内容脚本
属性中添加一个
“run\u at”:“document\u end”

document\u end
中,DOM完成后将注入脚本文件。这样,
文档
就可以找到丢失的按钮:)


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

manifest.json

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

document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);
{
  "manifest_version": 2,
  "name": "my extension",
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"]          
      }
  ]
}
document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);