Safari doesn't call iframe onload when src is not valid site

人盡茶涼 提交于 2019-12-13 16:26:28

问题


For the following iframe, Safari never calls the onload function and doesn't display anything in the iframe. All other browsers I've tested do call onload and display a default error web page.

<html>
<body>
<iframe src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com"
        onload="alert('iframe loaded');">
</iframe>
</body>
</html>

Why is this happening? If there is no solution to this problem, then I need to find a way to detect if an iframe fails to load.


回答1:


I just the other day stumbled upon this post with a workaround for the missing load event in Safari. The post is from 2011 but seems to be still valid.

The solution proposed there for Safari is to check for the readyState event on the iframe's document like so:

<iframe id="ifra" src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com"
        onload="alert('iframe loaded');">
</iframe>
<script>
    var iframe = document.getElementById('ifra'),
        doc = iframe.contentDocument || iframe.contentWindow;
    if (doc.document) doc = doc.document;
    var _timer = setInterval(function() {
        if (doc.readyState == 'complete') {
            clearInterval(_timer);
            alert('iframe ready');
        }
    }, 1000);
</script>

As per Mozilla's documentation on contentDocument, you wouldn't need to include the workaround with the contentWindow when running this script only in Safari, but I kept it in here in case you want to use it across browsers.



来源:https://stackoverflow.com/questions/23355179/safari-doesnt-call-iframe-onload-when-src-is-not-valid-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!