html5-跨文档消息传递-postMessage()

本文介绍了如何使用HTML5的postMessage()方法实现在不同页面之间的消息传递,尤其适用于两个页面存在关联的情况,如一个页面打开另一个页面。通过示例展示了如何在不同环境下发送和接收消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTML5跨文档消息传递-postMessage()

如果要实现从一个页面向到另一个页面传递消息,使用html5的API就可
以实现。postMessage()就是用来试下跨文档消息传递的,不过这个API有局限,
只能新开的页面传递消息(内嵌也可以)。

一个页面内嵌另一个页面

// index.jsp页面(源页面)
<iframe src="http://localhost:8090/a"></iframe>
    <script type="text/javascript">
        // 跨域发送数据到目标源
        window.onload = function () {
            document.getElementsByTagName("iframe")[0].contentWindow.postMessage({name: 'wujiang'}, "http://localhost:8090")
        }
        // 监听目标源发送过来的数据
        window.addEventListener('message', function (e) {
            console.log('http://localhost:8090/a.ftl ===> http://localhost:8080/index.jsp')
            console.log(e)
        })
    </script>
<script>
    // a.ftl页面(目标页面)
    // 监听其他窗口是否发送数据
    if (window.addEventListener) {
        window.addEventListener('message', function (e) {
            if (e.origin !== 'http://localhost:8080') {
                return
            }
            console.log('http://localhost:8080/index.jsp ===> http://localhost:8090/a.ftl')
            // 打印数据
            console.log(e)
            // 回传数据
            e.source.postMessage('hello wujiang', e.origin)
        }, false)
    } else if (window.attachEvent) {
        window.attachEvent('onmessage', function (e) {
            if (e.origin !== 'http://localhost:8080') {
                return
            }
            console.log('http://localhost:8080/index.jsp ===> http://localhost:8090/a.ftl')
            // 打印数据
            console.log(e)
            // 回传数据
            e.source.postMessage('hello wujiang', e.origin)
        }, false)
    }
</script>
控制台打印如下:

index.jsp到a.ftl
data:发送的数据
origin:源IP地址
source:源窗口
可以通过source返回数据到源窗口

一个页面打开另一个页面

// 打开一个新窗口
        var newWin = window.open('http://localhost:8090/a')
        // 向新窗口发送数据
        setTimeout(function () {
            console.log('http://localhost:8080/a.jsp ===> http://localhost:8090/a.ftl')
            newWin.postMessage({name: 'wujiang'}, 'http://localhost:8090')
        }, 1000)
依然是打开端口为8090的a.ftl页面,代码同上,打印内容同上。

小结

如果2个页面之间有关联(一个页面由另一个页面打开),则可以使用postMessage()方法实现通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值