您好,欢迎来到测品娱乐。
搜索
您的当前位置:首页html5跨域通讯之postMessage的用法总结_html5教程技巧

html5跨域通讯之postMessage的用法总结_html5教程技巧

来源:测品娱乐


postMessagePortal.html 页面代码

代码如下:

标题


var targetOrigin = "http://22527.vhost20.boxcdn.cn";

var defaultTitle = "Portal";
var notificationTimer = null;

function messageHandler(e) {
if (e.origin == targetOrigin) {
notify(e.data);
} else {
// ignore messages from other origins
}
}

function sendString(s) {
document.getElementById("widget").contentWindow.postMessage(s, targetOrigin);
}


function notify(message) {
stopBlinking();
blinkTitle(message, defaultTitle);
}

function stopBlinking() {
if (notificationTimer !== null) {
clearTimeout(notificationTimer);
}
document.title = defaultTitle;
}

function blinkTitle(m1, m2) {
document.title = m1;
notificationTimer = setTimeout(blinkTitle, 1000, m2, m1)
}

function sendStatus() {
var statusText = document.getElementById("statusText").value;
sendString(statusText);
}

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);

跨域通讯


传递信息:




postMessageWidget.html页面的代码

代码如下:

标题

var targetOrigin = "http://www.weixiu0376.cn";

// TODO whitelist array

function messageHandler(e) {
if (e.origin === "http://www.weixiu0376.cn") {
document.getElementById("status").textContent = e.data;
} else {
// ignore messages from other origins
}
}

function sendString(s) {
window.top.postMessage(s, targetOrigin);
}

function loadDemo() {
document.getElementById("actionButton").addEventListener("click",
function() {
var messageText = document.getElementById("messageText").value;
sendString(messageText);
}, true);

}
window.addEventListener("load", loadDemo, true);
window.addEventListener("message", messageHandler, true);

显示接收信息:


Copyright © 2019- cepb.cn 版权所有 湘ICP备2022005869号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务