欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5跨域通讯之postMessage的用法总结

程序员文章站 2023-11-17 15:04:52
本文是对html5跨域通讯之postMessage的用法进行了详细的总结介绍,需要的朋友可以过来参考下,希望对大家有所帮助... 13-11-07...

postmessageportal.html 页面代码

复制代码
代码如下:

<!doctype html>
<title>标题</title>
<link rel="stylesheet" href="styles.css">
<link rel="icon" href="http://apress.com/favicon.ico">
<script></p> <p>var targetorigin = "http://22527.vhost20.boxcdn.cn";</p> <p>var defaulttitle = "portal";
var notificationtimer = null;</p> <p>function messagehandler(e) {
if (e.origin == targetorigin) {
notify(e.data);
} else {
// ignore messages from other origins
}
}</p> <p>function sendstring(s) {
document.getelementbyid("widget").contentwindow.postmessage(s, targetorigin);
}</p> <p>
function notify(message) {
stopblinking();
blinktitle(message, defaulttitle);
}</p> <p>function stopblinking() {
if (notificationtimer !== null) {
cleartimeout(notificationtimer);
}
document.title = defaulttitle;
}</p> <p>function blinktitle(m1, m2) {
document.title = m1;
notificationtimer = settimeout(blinktitle, 1000, m2, m1)
}</p> <p>function sendstatus() {
var statustext = document.getelementbyid("statustext").value;
sendstring(statustext);
}</p> <p>function loaddemo() {
document.getelementbyid("sendbutton").addeventlistener("click", sendstatus, true);
document.getelementbyid("stopbutton").addeventlistener("click", stopblinking, true);
sendstatus();
}
window.addeventlistener("load", loaddemo, true);
window.addeventlistener("message", messagehandler, true);</p> <p></script></p> <p><h1>跨域通讯</h1>
传递信息:<input type="text" id="statustext" value="online">
<button id="sendbutton">确定</button>


<iframe id="widget" src="http://22527.vhost20.boxcdn.cn/postmessagewidget.html"></iframe>
<p>
<button id="stopbutton">停止标题闪烁</button>
</p>

postmessagewidget.html页面的代码

复制代码
代码如下:

<!doctype html>
<title>标题</title>
<link rel="stylesheet" href="styles.css">
<script></p> <p>var targetorigin = "http://www.weixiu0376.cn";</p> <p>// todo whitelist array</p> <p>function messagehandler(e) {
if (e.origin === "http://www.weixiu0376.cn") {
document.getelementbyid("status").textcontent = e.data;
} else {
// ignore messages from other origins
}
}</p> <p>function sendstring(s) {
window.top.postmessage(s, targetorigin);
}</p> <p>function loaddemo() {
document.getelementbyid("actionbutton").addeventlistener("click",
function() {
var messagetext = document.getelementbyid("messagetext").value;
sendstring(messagetext);
}, true);</p> <p>}
window.addeventlistener("load", loaddemo, true);
window.addeventlistener("message", messagehandler, true);</p> <p></script>
<p>显示接收信息: <strong id="status"></strong><p>
<div>
<input type="text" id="messagetext" value="填写消息内容">
<button id="actionbutton">发送消息</button>
</div>