【发布时间】:2016-04-10 17:13:12
【问题描述】:
我想全局重新定义一个 createElement 方法,但不幸的是它只在主文档中有效,在 iframe 中被忽略。让我们来看看这个示例代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
old_createElement = document.createElement;
document.createElement = function(el_type) {
new_el = old_createElement.call(this, el_type);
new_el.style.color="red";
return new_el;
};
</script>
</head>
<body bgcolor="white">
<iframe id="iframe1"></iframe>
<script type="text/javascript">
window.setTimeout(function(){
iframe_el = document.getElementById("iframe1").contentDocument.createElement("div");
iframe_el.innerHTML = 'inside iframe';
document.getElementById("iframe1").contentDocument.body.appendChild(iframe_el);
},50);
no_iframe_el=document.createElement('div');
no_iframe_el.innerHTML = 'outside of iframe';
document.body.appendChild(no_iframe_el);
</script>
</body>
</html>
当我在浏览器中打开时,在主文档中创建的元素是红色的,正如预期的那样,但 iframe 中的元素是黑色的。
问题是我只能控制文档 HEAD 部分中包含的脚本。换句话说,我不知道 HTML 源代码中稍后会有多少 iframe,或者它们将如何命名,或者它们是否是通过用户的 Javascript 添加的。
我的问题是:如何全局更改方法,让 iframe 中创建的所有元素也使用这种新样式?
非常感谢!
【问题讨论】:
-
每个 iframe 都有自己的范围/全局范围/dom/css/whatever 所以你的 document.createElement 在那里不可用
-
答案是:不。因为:安全。你不能写你的病毒或任何东西
标签: javascript html dom iframe