简体   繁体   English

如何在 Chrome 扩展的标记后添加一些 DOM 元素?

[英]How do I add some DOM elements just after <body> tag from a Chrome Extension?

I want to insert some DOM nodes to a webpage before it's rendered.我想在网页呈现之前将一些 DOM 节点插入到网页中。 I don't have control of the page so I can only create a chrome extension to do so.我无法控制该页面,所以我只能创建一个 chrome 扩展程序来这样做。 For instance, I want to insert a <p>hello world</p> just after the <body> tag.例如,我想在<body>标记之后插入一个<p>hello world</p> So far as I know I can only insert <script> before the <body> , in the <head> .据我所知,我只能在<body>之前,在<head>中插入<script> > 。 However, when I try to access <body> from that script, it's not working.但是,当我尝试从该脚本访问<body>时,它不起作用。

What can I do to achieve this?我该怎么做才能实现这一目标?

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test Page</title>
    <style>
        
    </style>
    <script type="text/javascript">
      var a = document.querySelector('body');
      alert(a) // null
    </script>
</head>
<body>
    <script type="text/javascript">
      var a = document.querySelector('body');
      alert(a) // [object HTMLBodyElement]
    </script>
</body>
</html>

There seems to be an issue with the permissions you use in your chrome extension.您在 Chrome 扩展程序中使用的权限似乎存在问题。 In order to access the current page, you need the activeTab permission and also, you need to check whether you have allowed the current URL in the extension's manifest.json file.为了访问当前页面,您需要有activeTab权限,并且您需要检查您是否允许扩展程序的manifest.json文件中的当前URL。 Check the example file below:检查下面的示例文件:

{
  "name": "Your chrome extension",
  "description": "You can add anything to the body",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["content-script.js"]
    }
  ],
  "browser_action": {
    "default_title": "Append Test Text"
  },
  "manifest_version": 2
}

Then, your content-script.js file should look like the below:然后,您的 content-script.js 文件应如下所示:

var p = document.createElement("p"); 
p.innerHTML = "Hello World";
document.body.insertBefore(p);

You can find more information about Chrome extensions by the official docs: Click Here您可以通过官方文档找到有关 Chrome 扩展的更多信息:单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM