我正在尝试在iframe内添加一些html元素,以个性化网站。我正在构建一个浏览器扩展程序,因此不存在跨域问题。我已经有了iframe:
<iframe id="container" src="http://www.google.com">
<p>Your browser does not support iframes.</p>
</iframe>
然后,当文档已经加载时,我创建元素并将其插入... 但它从未显示在 iframe 中。但是我可以获取 iframe 中已存在的元素并更改其属性。所以,我可以访问元素,但不能创建新元素?为什么?
var ifr = document.querySelector("#container");
var ifrDoc = ifr.contentWindow || ifr.contentDocument;
if (ifrDoc.document) ifrDoc = ifrDoc.document;
var elem = ifrDoc.createElement("div");
elem.innerHTML = "Demo Box";
elem.style.width = "50px";
elem.style.height = "50px";
elem.style.position = "absolute";
elem.style.background = "red";
ifrDoc.body.appendChild(elem);
这里有一个JSFiddle演示,以便更好地了解问题(请记住扩展程序拥有其他权限):http://jsfiddle.net/TH48e/40/ 有什么想法吗?