Luk*_*e G 71 javascript google-chrome google-chrome-extension
如果页面标题包含特定文本,如何向加载的页面添加一些HTML代码?
Chrome扩展程序是我的新理由,非常感谢您的帮助.
Sud*_*han 133
您可以将以下代码作为添加某些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"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
Output您会看到一个添加到所需页面的按钮

Tec*_*ode 11
@Sudarshan 的答案解释了页面的特殊性,很好,但是添加的评论怎么样?以下是如何以更简单、更实用的方式完成他错过的事情,以修改现有内容或在页面上创建内容,最简单的方法是:
调整
单项修改:
document.getElementById("Id").innerHtml = this.innerHtml + "<some code here>";
Run Code Online (Sandbox Code Playgroud)
或修改属性:
document.getElementById("Id").class = "classname";
//or ->
document.getElementById("Id").style.color = "#a1b2c3";
Run Code Online (Sandbox Code Playgroud)
要添加多行代码,请执行以下操作:
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 -->
`
;
Run Code Online (Sandbox Code Playgroud)
创造
大型代码注入(来自不久前完成的编码项目的示例)请参阅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>
`);
Run Code Online (Sandbox Code Playgroud)
参考:
| 归档时间: |
|
| 查看次数: |
50820 次 |
| 最近记录: |