一个简单的postMessage实例

跨文档消息传送(cros-document Message),指的是在不同域的页面间传递消息。

以下是我用webstorm测试的使用postMessage在iframe和父级之间传参。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        iframe{
            width: 300px;
            height: 300px;
        }
    </style>
</head>
<body>

<iframe src="http://localhost:63342/JQuery%E5%95%86%E5%9F%8E%E5%AE%9E%E4%BE%8B/iframe.html?_ijt=jrpcgmgcep8n6ppfh53s3fcttm" frameborder="1"></iframe>




<script>
    console.log(window.location)
    let iframe = document.querySelector("iframe")
    iframe.onload=function () {
        setTimeout(function () {
            iframe.contentWindow.postMessage('WXS','http://localhost:63342')
        },1000)
    }

    window.addEventListener("message",function (res) {
        console.log(res)
    })

</script>
</body>
</html>

但我发现这种方法好像并不能跨域,子父页面必须要在同域之下。即相同的协议(http),相同的域名(www.locaolhost),相同的端口号(63342)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值