当前位置: 移动技术网 > IT编程>网页制作>Html5 > html5跨域通讯之postMessage的用法总结

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

2019年07月25日  | 移动技术网IT编程  | 我要评论

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>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网