【笔记】H5 postMessage跨域发送消息

* 此实例为主页面Iframe页面发送消息

 发送端】主页面端代码

var popup = document.querySelector('#ifm'); //获取Iframe对象
var targetorigin = "https://locahost:80" //目标窗口(Iframe)的域名端口

//注册message监听事件,接收目标域回发消息
window.addEventListener("message", function (event) {
    //允许目标地址的域名回发消息
    //如果消息来源地址与目标地址一致,则允许接收消息
    if (event.origin === targetorigin) {
        //返回消息为"OK",执行自定义逻辑
        if (event.data == "OK") {
            //自定义逻辑
            //window.location.href = "";
        }
    }
});

//Ajax判断Iframe地址是否能正常访问
$.ajax({
    url: $("#ifm").attr("src"),
    type: 'GET',
    async: false,
    success: function (data) {
        //页面访问地址有效,发送消息
        popup.contentWindow.postMessage("测试消息", targetorigin);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        //访问失败,提示或者执行其他逻辑
        //window.location.href = "";
    }
});

接收端】目标窗口(Iframe)代码

function ReceiveMessage(event) {
    //主页面域名端口,请自行配置
    var origin = "https://localhost:8081";

    // 我们能信任信息来源吗?
    if (event.origin !== origin) {
        console.log("非法消息,已停止响应!");
        return;
    }
    else {
        //验证成功,执行自定义方法
        // event.data 是主页面发送的消息,这个例子接收的为:"测试消息"
        TestFunction(event.data);
    }
    // event.source 就当前弹出页的来源页面
    // 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把event.source
    // 作为回信的对象,并且把event.origin作为targetOrigin
    // 这里给主页面回发了一个“OK”的消息
    event.source.postMessage("OK", event.origin);
}

//注册Iframe页面的message监听事件
window.addEventListener("message", ReceiveMessage, false);

猜你喜欢

转载自blog.csdn.net/Csongxuan/article/details/116202833