【问题标题】:Making postMessage() and addEventListener() compatible with IE8使 postMessage() 和 addEventListener() 与 IE8 兼容
【发布时间】:2015-01-29 14:43:00
【问题描述】:

我正在做一个项目,我们需要同时使用postMessage()addEventListener(),但我们想让应用程序与主流浏览器兼容。因为仍然有人(是的,他们存在,是的,他们应该被烧掉)使用 Internet Explorer 8,所以我们需要使上述两种方法兼容。

我编写了下面的代码,按照this answer 中的建议,通过使用attachEvent() 来使addEventListener() 兼容。但是,postMessage() 仍然无法正常工作,因此我按照this website 的建议添加了超时。这不起作用,我真的很难使应用程序兼容。它不会引发任何错误,而且我还可以看到我的应用程序已向 iframe 源发送了一条消息,但该消息从未被处理。

<script type="text/javascript">
    function ready()
    {
        window.setTimeout(function() {
            document.getElementById("editor").contentWindow.postMessage("A", "domain here");
        }, 0);
    }

    function receiveMessage(event)
    {
        if (event.origin !== "domain here")
            return;
    }

    window.setTimeout(function() {
        if (window.addEventListener) {
            window.addEventListener("message", receiveMessage, false);
        }
        else {
            window.attachEvent("message", receiveMessage);
        }
    }, 0);
</script>

我的第二个页面上有一个类似的脚本(正在加载到 iframe 中),它接收一条消息并发回一条消息。所有主要浏览器都在发送和接收这两条消息,所以问题是:如何使上述脚本与 Internet Explorer 8 兼容?

再说一次:我同意我们不应该关心使用 Internet Explorer 8 的人,而是应该烧掉他们,因为他们仍在使用它:但是这意味着我们将不得不烧掉我们的客户端,这是我们无法做到的。所以是的,我真的需要让它兼容。

如果您想知道:getElementById("editor") 捕获如下定义的 iframe:

<iframe src="frameListener.html" class="editor" id="editor" onload="ready()"></iframe>

【问题讨论】:

    标签: javascript internet-explorer-8 addeventlistener postmessage


    【解决方案1】:

    你错过了“开”

    window.attachEvent("onmessage", receiveMessage);
    

    【讨论】:

    • 是的,忽略我之前的评论,我忘了在两个页面上都添加它:现在它可以工作了:) 但是我现在收到一个不同的错误,所以我会修复它。感谢您的帮助,我会接受您的回答,因为它解决了我原来的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多