【问题标题】:can I catch exception of Iframe in parent window of Iframe我可以在 Iframe 的父窗口中捕获 Iframe 的异常吗
【发布时间】:2026-02-23 07:35:01
【问题描述】:

我在页面中有一个 IFrame,而 IFrame 有一些 JavaScript。在运行时 IFrame 中的 JavaScript 给出了我想在父窗口上捕获的异常。该怎么做?

<html> 
<head> 
<script type="text/javascript"> 
var frm123 = document.getElementById("frm123"); 
frm123.contentWindow.onerror = function() { 
    alert('error caught'); 
} 
function loadData() { 
    var oRTE = document.getElementById("frm123").contentWindow.document;
    oRTE.open(); 
    oRTE.write(txt123.value);
    oRTE.close();
} 
</script> 
</head> 
<body> 
<input type="button" onclick="loadData();" value="load"> 
<input type="text" id="txt123"> 
<iframe id = "frm123" > 
</body> 
</html>

【问题讨论】:

  • 邮政编码和异常信息

标签: javascript iframe exception-handling


【解决方案1】:

答案取决于你是否控制了 iframe 代码,以及它是否是同一个域。

如果域相同,则可以执行以下操作从包装文档中设置错误处理功能:

document.getElementById("myiframe").contentWindow.onerror=function() {
    alert('error!!');
    return false;
}

确保在设置错误处理程序之前等待 iframe 完成加载。

如果不是同一个域但你可以控制 iframe 内容(两个域都在你的控制之下),你可以通过使用跨域通信框架(谷歌它或自己构建)与外框架通信,即通过在 iframe 中设置 onerror 处理程序来捕获 iframe 中的错误,并通过框架将其发送到外部文档。

如果不是同一个域并且您无法控制 iframe,则由于安全限制,外部文档无法知道其中发生了什么。

【讨论】:

  • 页面加载过程中出现异常怎么办?
  • 那么你会遇到问题,因为你无法从外部控制它。
【解决方案2】:

.onError() 函数无法正常工作的原因可能很少,这可能是因为跨域 URL 的原因,您应该在实际加载 iFrame 之前进行检查并为此使用

var url = "google.com"
var loading_url = "/empty.html"
document.getElementById("iframe").src = loading_url;
$.ajax({
url: url,
type: 'GET',
complete: function(e, xhr, settings){
     if(e.status === 200){
          document.getElementById("iframe").src = url;
     }
  }
});

这将无法跨域工作,在这种情况下状态码为 0。

要检查的另一件事是.onError() 处理程序,请从下面的示例中检查它是否符合您的条件

How can I handle errors in loading an iframe?

还有许多其他选项或调整来处理此类错误:

if (frameDoc.title == 'title of page after expection occur')

还将使用 iFrame 的 .onLoad() 事件来完成工作。

【讨论】:

    【解决方案3】:

    唯一的方法是如果框架在同一个域上,在这种情况下你可以从父级:

    iframe.contentWindow.onerror = function(){
        // handle error
    }
    

    【讨论】:

    • @ArifHasan 在您的问题中写下上述代码,以便其他人可以帮助您
    最近更新 更多