Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

javascript - can I catch exception of Iframe in parent window of Iframe

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer depends on whether or not you have control of the iframe code, and whether or not it is the same domain.

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;
}

make sure you wait for the iframe to finish loading before setting the error handler.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...