postMessagePortal.html 页面代码
标题
<script>
<p>var targetOrigin = "http://22527.vhost20.boxcdn.cn";
<p>var defaultTitle = "Portal";<br />var notificationTimer = null;
<p>function messageHandler(e) {<br /> if (e.origin == targetOrigin) {<br /> notify(e.data);<br /> } else {<br /> // ignore messages from other origins<br /> }<br />}
<p>function sendString(s) {<br /> document.getElementById("widget").contentWindow.postMessage(s, targetOrigin);<br />}
<p><br />function notify(message) {<br /> stopBlinking();<br /> blinkTitle(message, defaultTitle);<br />}
<p>function stopBlinking() {<br /> if (notificationTimer !== null) {<br /> clearTimeout(notificationTimer);<br /> }<br /> document.title = defaultTitle;<br />}
<p>function blinkTitle(m1, m2) {<br /> document.title = m1;<br /> notificationTimer = setTimeout(blinkTitle, 1000, m2, m1)<br />}
<p>function sendStatus() {<br /> var statusText = document.getElementById("statusText").value;<br /> sendString(statusText);<br />}
<p>function loadDemo() {<br /> document.getElementById("sendButton").addEventListener("click", sendStatus, true);<br /> document.getElementById("stopButton").addEventListener("click", stopBlinking, true);<br /> sendStatus();<br />}<br />window.addEventListener("load", loadDemo, true);<br />window.addEventListener("message", messageHandler, true);
<p></script>
跨域通讯
传递信息:
postMessageWidget.html页面的代码
标题
<script>
<p>var targetOrigin = "http://www.weixiu0376.cn";
<p>// TODO whitelist array
<p>function messageHandler(e) {<br /> if (e.origin === "http://www.weixiu0376.cn") {<br /> document.getElementById("status").textContent = e.data;<br /> } else {<br /> // ignore messages from other origins<br /> }<br />}
<p>function sendString(s) {<br /> window.top.postMessage(s, targetOrigin);<br />}
<p>function loadDemo() {<br /> document.getElementById("actionButton").addEventListener("click",<br /> function() {<br /> var messageText = document.getElementById("messageText").value;<br /> sendString(messageText);<br /> }, true);
<p>}<br />window.addEventListener("load", loadDemo, true);<br />window.addEventListener("message", messageHandler, true);
<p></script>
显示接收信息: