can I catch exception of Iframe in parent window of Iframe

前端 未结 3 1662
名媛妹妹
名媛妹妹 2020-12-15 06:30

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?



        
3条回答
  •  爱一瞬间的悲伤
    2020-12-15 06:55

    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.

提交回复
热议问题