为什么postMessage脚本在IE8中不起作用?

时间:2013-02-05 17:27:07

标签: javascript iframe postmessage

经过广泛的研究后,看起来这应该可行,但在IE8中,letgo函数永远不会被调用...任何帮助?

<script type="text/javascript">
    function resizeCrossDomainIframe() {        

        if (window.addEventListener) {
            window.addEventListener('message', letsgo, false);
        } else if (window.attachEvent) {
            window.attachEvent('onmessage', letsgo);
        }
    }
    function letsgo(event) {
        var iframe = document.getElementById('my_iframe');
        if (event.origin !== 'http://mysite.com') return; // only accept messages from the specified domain
        if (isNaN(event.data)) return; // only accept something which can be parsed as a number
        var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
        iframe.height = height + "px";
    }
</script>
    <iframe src='http://mysite.com/products/default.aspx?iframe=true&partnerid=222&site=localhost:62014' frameborder="0" width="100%" scrolling="auto" style="min-height: 750px; min-width: 600px; background-color: #fff;"  id="my_iframe" onload="resizeCrossDomainIframe();">
    </iframe>

1 个答案:

答案 0 :(得分:6)

我明白了,一定是竞争条件。我拿出了货物。

<script type="text/javascript">


        if (window.addEventListener) {
            window.addEventListener('message', letsgo, false);
        } else if (window.attachEvent) {
            window.attachEvent('onmessage', letsgo);
        }

    function letsgo(event) {
        var iframe = document.getElementById('my_iframe');
        if (event.origin !== 'http://mysite.com') return; // only accept messages from the specified domain
        if (isNaN(event.data)) return; // only accept something which can be parsed as a number
        var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
        iframe.height = height + "px";
    }
</script>
    <iframe src='http://mysite.com/products/default.aspx?iframe=true&partnerid=222&site=localhost:62014' frameborder="0" width="100%" scrolling="auto" style="min-height: 750px; min-width: 600px; background-color: #fff;"  id="my_iframe" >
    </iframe>