我想构建一个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/
正如您所看到的,它适用于普通网页 但它在我的扩展中不起作用。
但我的代码是一样的。我不知道它为什么不起作用。
答案 0 :(得分:1)
默认情况下,inline script won't be executed。尝试将JS代码解压缩到外部JavaScript文件,并将其作为脚本标记包含在内。
的manifest.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);
}