[英]Javascript function injected by removed iframe
是否可以将在iframe中定义的javascript函数注入父窗口,以便即使在删除iframe之后也可以使用它? 这是我的工作:在iframe中,我有:
var f = function(){console.log("iframe function")}
window["iframeFunction"] = f;
父级可以成功调用该函数,直到iframe可用为止。之后,它将不起作用。
假设这是您的iframe(ifr.htm)-
<html>
<head>
<script type="text/javascript">
function func() {
window.top.window.f = function() {
alert('iframe hack');
}
}
window.onload = function() {
alert('iframe loaded');
func();
};
</script>
</head>
<body>
this is the test iframe.
</body>
</html>
这是您的父窗口-
<html>
<head>
<script type="text/javascript">
window.onload = function() {
i = document.getElementById('iframe'); //remove the iframe
i.parentNode.removeChild(i);
window.f(); //you can still call f() method
};
</script>
</head>
<body>
this is the parent window.
<iframe src="ifr.htm" id="iframe"></iframe>
</body>
</html>
这基本上是使用top
访问父级并为其添加功能。 因此,即使将iframe
从DOM中删除,该功能仍会保留,因为它已添加到父项中。
根据浏览器支持要求,我建议使用postMessage 。 优点是:
编辑:即使您想要具有由iframe指定的标签的父级全局名称空间中的可用功能,第2点仍然适用。
编码:
// In your iframe
var f = function(){console.log("iframe function")}
window.top.postMessage({f:f}, '*');
// In the parent
window.addEventListener('message', function capturePassedFunction(e){
// If you want to keep this in scope
var f = e.data.f;
// You can still chuck it on the `window` object if you want!
window.f = e.data.f;
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.