问题描述
我在页面中有一个IFrame,IFrame有一些JavaScript。在运行时,IFrame中的JavaScript会提供异常,我想在父窗口中捕获。如何做?
I have an IFrame in a page and IFrame has some JavaScript. At run time JavaScript in IFrame gives exception which i want to catch on parent window. How to do that?
<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>
推荐答案
答案取决于你是否控制iframe代码,以及它是否是相同的域。
The answer depends on whether or not you have control of the iframe code, and whether or not it is the same domain.
如果同一个域,那么你可以执行以下操作来设置包装文档中的错误处理函数: / p>
If same domain then you can do the following to set the error handling function from the wrapping document:
document.getElementById("myiframe").contentWindow.onerror=function() {
alert('error!!');
return false;
}
确保在设置错误处理程序之前等待iframe完成加载。
make sure you wait for the iframe to finish loading before setting the error handler.
如果它不是同一个域,但是您可以控制iframe内容(这两个域都在您的控制之下),您可以使用跨域与外部框架进行通信通信框架(google it或自己构建),即通过在iframe中设置onerror处理程序来捕获iframe中的错误,并将其通过框架发送到外部文档。
If it's not the same domain but you have control of the iframe content (both domains are under your control), you can communicate with the outer frame by using a cross domain communication framework (google it or build it yourself), i.e. catch the error in the iframe by setting the onerror handler from within the iframe and send it through the framework to the outer document.
如果它不是同一个域,并且您没有iframe的控制权,那么外部文档就没有办法知道由于安全性限制而发生了什么。
If it's not the same domain and you don't have control of the iframe, there's no way for the outer document to know what's going on inside it because of security constraints.
这篇关于我可以在Iframe的父窗口中捕获Iframe的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!