Home > Web Front-end > H5 Tutorial > Summary of usage of postMessage in html5 cross-domain communication_html5 tutorial skills

Summary of usage of postMessage in html5 cross-domain communication_html5 tutorial skills

WBOY
Release: 2016-05-16 15:48:45
Original
1676 people have browsed it

postMessagePortal.html 页面代码

复制代码
代码如下:


标题


<script></p> <p>var targetOrigin = "http://22527.vhost20.boxcdn.cn";</p> <p>var defaultTitle = "Portal";<br>var notificationTimer = null;</p> <p>function messageHandler(e) {<br> if (e.origin == targetOrigin) {<br> notify(e.data);<br> } else {<br> // ignore messages from other origins<br> }<br>}</p> <p>function sendString(s) {<br> document.getElementById("widget").contentWindow.postMessage(s, targetOrigin);<br>}</p> <p><br>function notify(message) {<br> stopBlinking();<br> blinkTitle(message, defaultTitle);<br>}</p> <p>function stopBlinking() {<br> if (notificationTimer !== null) {<br> clearTimeout(notificationTimer);<br> }<br> document.title = defaultTitle;<br>}</p> <p>function blinkTitle(m1, m2) {<br> document.title = m1;<br> notificationTimer = setTimeout(blinkTitle, 1000, m2, m1)<br>}</p> <p>function sendStatus() {<br> var statusText = document.getElementById("statusText").value;<br> sendString(statusText);<br>}</p> <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> <p></script>

跨域通讯


传递信息:








postMessageWidget.html页面的代码

复制代码
代码如下:


标题

<script></p> <p>var targetOrigin = "http://www.weixiu0376.cn";</p> <p>// TODO whitelist array</p> <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> <p>function sendString(s) {<br> window.top.postMessage(s, targetOrigin);<br>}</p> <p>function loadDemo() {<br> document.getElementById("actionButton").addEventListener("click",<br> function() {<br> var messageText = document.getElementById("messageText").value;<br> sendString(messageText);<br> }, true);</p> <p>}<br>window.addEventListener("load", loadDemo, true);<br>window.addEventListener("message", messageHandler, true);</p> <p></script>

显示接收信息:






Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template