使用chrome扩展修改已加载页面的HTML

时间:2012-12-28 11:33:27

标签: javascript google-chrome google-chrome-extension

如果页面标题包含特定文本,如何向加载的页面添加一些HTML代码?

Chrome扩展程序是我的新理由,非常感谢您的帮助。

2 个答案:

答案 0 :(得分:128)

参考文献:

您可以将以下代码作为添加一些HTML代码的参考。

manifest.json

此文件将内容脚本注册到扩展名。

{
"name":"Inject DOM",
"description":"http://stackoverflow.com/questions/14068879",
"version":"1",
"manifest_version":2,
"content_scripts": [
    {
      "matches": ["http://www.google.co.in/*","https://www.google.co.in/*"],
      "js": ["myscript.js"]
    }
  ]
}

myscript.js

一个简单的脚本,用于向Google页面添加按钮

// Checking page title
if (document.title.indexOf("Google") != -1) {
    //Creating Elements
    var btn = document.createElement("BUTTON")
    var t = document.createTextNode("CLICK ME");
    btn.appendChild(t);
    //Appending to DOM 
    document.body.appendChild(btn);
}

Output

您会看到一个添加到所需页面的按钮

enter image description here

答案 1 :(得分:1)

@Sudarshan的答案解释了页面的特殊性,很好,但是添加的注释又如何呢?这是一种以更轻松,更实际的方式做他错过的事情 修改现有内容或在页面上创建内容的最简单方法是:

  

修改

单项修改:

document.getElementById("Id").innerHtml = this.innerHtml + "<some code here>";

或修改属性:

document.getElementById("Id").class = "classname";

//or ->

document.getElementById("Id").style.color = "#a1b2c3";

要添加多行代码,请执行以下操作:

document.getElementById("Id").innerHtml = this.innerHtml + `
 <some code here>                                                            <!-- Line 1 -->
 and we're on multiple lines!` + "variables can be inserted too!" + `        <!-- Line 2 -->
 <this code will be inserted directly **AS IS** into the DOM                 <!-- Line 3 -->
`
;
  • 但是现在如何轻松插入元素?
  

创建

大代码注入(前一段时间编码项目的示例),请参见insertAdjacentHtml API

var bod = document.getElementsByTagName('body')[0];

bod.insertAdjacentHTML('afterbegin', `
    <div class="Boingy" id="Boingy">
        <div class="Boihead" id="BoiHead">
            <div class="deXBox" id="deXBox">
                <div class="Tr-Bl_Button" style="height: 25px;width: 2px;margin-left: 11.65px;background-color: gray;transform: rotate(45deg);-ms-transform: rotate(45deg);-webkit-transform: rotate(45deg);Z-index: 1;">
                    <div class="Tl-Br_Button" style="height: 25px;width: 2px;background-color: gray;transform: rotate(90deg);-ms-transform: rotate(90deg);-webkit-transform: rotate(90deg);Z-index: 2;">
                        </div>
                    </div>
                </div>
            </div>
            <embed id="IframeThingyA" src="` + "url" + `" type="text/html">
            </embed>
        </div>
    `);

参考: