首页 > 解决方案 > 加载前在 iFrame 上设置事件侦听器

问题描述

假设我在example.com,并且我有一个 iFrame example.com。(是的,它们是相同的)我需要捕获 iFrame 中发生的错误。如何在 iFrame 中设置事件侦听器,然后它的脚本元素开始加载?

我以前看过它,例如在repl.it上。

标签: javascripthtmliframe

解决方案


你可以试试这样的 ->

<iframe id="myframe" src="https://google.ca"></iframe>



<script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

推荐阅读