HTML5学习之跨文档传输消息(七)

新标准中提供了文档之间直接的消息传输API。而且不限制跨域消息传递!
发送消息使用的是Window对象的postMessage(data,targetURL)方法就可以了,但给哪个window对象发送消息,就使用哪个window的实例来调用,注意这个细节。
文档默认监听一下message事件就可以接受消息了:window.addEventListener("message", function (ev) {});
监听消息事件:ev两个重要属性:ev.source指向发送消息的源window对象,ev.data来获取收到的消息数据
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

      <script>

          window.onload = function() {

              document.getElementById("btn").onclick = function() {

                  document.getElementById("f").contentWindow.postMessage(document.getElementById("t").value, "*");

              };

          };

    </script>

</head>

<body>

    <input id="t" type="text" />

    <input id="btn" type="button" />

    <iframe id="f" src="receiveMsg.html" ></iframe>

</body>

</html>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        window.onmessage = function (event) {

            //event.data  数据  event.origin 消息来源地址  event.source   源DOMWindow 对象

            alert(event.data);

            alert(event.origin);

            alert(event.source);

        }

    </script>

</head>

<body>



</body>

</html>

 

你可能感兴趣的:(html5)