html HTML5中提供的postMessage()功能示例(非常粗略和基本的概念证明示例)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html HTML5中提供的postMessage()功能示例(非常粗略和基本的概念证明示例)相关的知识,希望对你有一定的参考价值。

<DOCTYPE html>
<html>
    <head>
        <title>Parent Page</title>
    </head>
    <body>

        <h1 id="alter-me"></h1>

        <script type="text/javascript">
            /**
             * Compatibility stuff for it to work in all browsers.
             */
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

            /**
             * This listens to the evcent from the child iframe page
             */
            eventer(messageEvent,function(event) {
                document.getElementById('alter-me').innerHTML = event.data;
            },false);
        </script>

        <iframe src="http://somesite.com/iframe.html" style="width:930px;height:900px;border:none!important;"></iframe>

    </body>
</html>
<DOCTYPE html>
<html>
    <head>
        <title>The iFrame file included in the above parent page</title>
    </head>
    <body>
        <script type="text/javascript">
        /**
         * This will send every second
         */
        setInterval(function() {
            /**
             * The second parameter of the postMessage method must be the same as the 
             * domain it is passing the message to for it to work.
             */
            parent.postMessage("THE MESSAGE TO SEND TO THE PARENT PAGE", "http://parentsite.com");
        }, 1000);
        </script>
    </body>
</html>

以上是关于html HTML5中提供的postMessage()功能示例(非常粗略和基本的概念证明示例)的主要内容,如果未能解决你的问题,请参考以下文章

HTML5中window.postMessage,在两个页面之间的数据传递

postMessage处理iframe 跨域问题

postMessage处理iframe 跨域问题

html5 postmessage 是通过啥方式传参

使用HTML5中postMessage实现Ajax中的POST跨域问题

html5 postMessage解决跨域跨窗口消息传递