我想构建一个 Chrome 扩展程序。
有一次我必须使用 JavaScript 添加一些新的 html 标签,但它不起作用。
因此,我在本地网络服务器和扩展程序中尝试了这个小示例。
HTML
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">This is old</div>
<script>
document.body.onload = addElement;
function addElement () {
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is new!");
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
</body>
</html>
http://www.jsfiddle.net/yz9v8479/
如您所见,它对于普通网页来说效果很好。
但它在我的扩展中不起作用。
但是我的代码是一样的。我不知道为什么它不起作用。
最佳答案
默认情况下,inline script won't be executed 。尝试将 JS 代码提取到外部 JavaScript 文件并将其作为脚本标记包含在内。
list .json
{
"name": "36738850",
"version": "0.1",
"manifest_version": 2,
"browser_action": {
"default_title": "Your browser action title",
"default_popup": "popup.html"
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">This is old</div>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.body.onload = addElement;
function addElement() {
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is new!");
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
关于javascript - 使用 JS 添加 HTML 标签 | chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738772/