[英]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.