Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't IE8 handle iframe onload events?

Sample code:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function on_iframe_load() {
    document.getElementById('iframe_a').onload = function() {
        alert('Thanks for the visit!');
    };
}
</script>
</head>
<body>
<iframe name="iframe_a" id="iframe_a"></iframe>
<a href="http://www.example.com/" target="iframe_a" onclick="on_iframe_load();">Go!</a>
</body>
</html>

It works in all major browsers with no problem, but IE8 (and probably prior versions) don't understand it.

Update: Just came up with a solution, but I'm not sure if it's right coding. Please review:

<!DOCTYPE html>
<html>

    <head>
        <title></title>
        <script>
            var clicked = false;

            function activate() {
                clicked = true;
            }

            function pop() {
                if (clicked) {
                    alert('Thanks for the visit!');
                };
            }
        </script>
    </head>

    <body>
        <iframe name="iframe_a" onload="pop();"></iframe>
        <a href="http://www.example.com/" target="iframe_a" onclick="activate();">Go!</a>

    </body>

</html>
like image 904
Mori Avatar asked Oct 16 '12 08:10

Mori


1 Answers

Using inline attribute on iframe seems to fix this issue in IE8:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function onIframeLoad(iframe) {
    if(iframe.src) {
        alert('Thanks for the visit!');
    }
}
function onLinkClick(url) {
    document.getElementById('iframe_a').src = url;
}
</script>
</head>
<body>
<iframe id="iframe_a" onload="onIframeLoad(this);"></iframe>
<a href="http://www.example.com/" onclick="onLinkClick(this); return false;">Go!</a>
</body>
</html>

update by request:

You should try writing more unobtrusive javascript. Writing code in such way may prevent you from such strange bugs in IE.

<!DOCTYPE html>
<html>
<body>
    <iframe id="display-frame"></iframe>
    <a href="http://www.example.com/">Go!</a>
    <script>
        window.onload = function() {
            var iframe = document.getElementById('display-frame'),
                link = document.getElementsByTagName('a')[0];

            // load handler
            function onIframeLoad() {
                alert('Thanks for the visit!');
            }

            // event handlers
            if(iframe.addEventListener) iframe.addEventListener('load', onIframeLoad, false);
            else if(iframe.attachEvent) iframe.attachEvent('onload', onIframeLoad);

            link.onclick = function() {
                iframe.src = this.href;
                return false;
            }
        };
    </script>
</body>
</html>
like image 73
Inferpse Avatar answered Oct 02 '22 07:10

Inferpse