iframe跨域传递数据,完整简洁的代码

1 篇文章 0 订阅
1 篇文章 0 订阅

兼容

IE11+ && other

主要使用方法

window.otherWindow.postMessage(data,orign)

中文介绍文档 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

参数说明:
data: 发送的数据。接受范围:字符串、数字、对象、数组(不能包含当前页可执行方法,也就是不能传递Function)
orign:接收消息的域名,比如页面存在多个iframe,可以通过设置这个值,指定哪个iframe接收消息,如果所有页面都接收,可以填写 “*”。

测试环境

创建两个 html 分别为A.html、B.html,通过localhost和127.0.0.1进行跨域测试。
A.html 使用 http://127.0.0.1/xxx/A.html 访问
B.html 使用 http:// localhost/xxx/B.html 访问

具体代码

A.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>页面A</title>
</head>
<body>
    

    <div>
        <div>这是A页面</div>
        <button onclick="senMsg()">发送数据给子页面</button>

        <div id="msgView" style="white-space: pre-line; background: #009; color:#fff;"></div>
    </div>

    <iframe id="myFrame" style="width:800px; height:300px; border:none; margin: 20px 0; " src="http://localhost/kuayu/B.html"></iframe>


    <script>
        /*
        *  父页向子页面发送数据
        */
        var senMsg = function(){
            var myFrame = document.getElementById('myFrame');
            myFrame.contentWindow.postMessage({
                title: "标题",
                msg: 'Hello B Page!',
                date: Date.now()
            },"http://localhost")
        }

        // 监听 子页面传递的消息
        window.addEventListener('message',function(event){
            var txt = "这是A页面,收到子页面发送的数据:\n"+event.data;
            console.log('----------- '+txt);
            document.getElementById('msgView').innerHTML = txt;
        }, false);
    </script>

</body>
</html>
B.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>页面B</title>
</head>
<body style="background: #efefef;">

    <div>
        <div>这是B页面</div>
        <p>
            <button onclick="senMsgToParent()">发送数据给父页面</button>
        </p>
    </div>

    <div style="border:1px solid #090; padding:10px;">
        <p><h3>父页面传来的消息</h1></p>
        <p id="msgView"></p>
    </div>

    <script>
        window.addEventListener('message',function(event){
            document.getElementById('msgView').innerHTML =  JSON.stringify(event.data);
        }, false);

        // 发送数据给父页面
        var senMsgToParent = function(){
            window.parent.postMessage("Hello I'm B Page! \n Time now:"+Date.now(), "*");   
        }
    </script>
</body>
</html>

结果示例图

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Web 开发中,当网页中包含来自不同名的 iframe(内嵌框架)时,由于浏览器的同源策略限制,iframe 之间的直接通信会受到限制。为了实现 iframe 之间的通信,可以使用 postMessage 方法。 postMessage 是一种 HTML5 提供的文档消息传递机制,它允许在不同窗口或 iframe 之间发送消息。通过 postMessage,可以在不同名之间进行安全的双向通信。 使用 postMessage 进行通信的步骤如下: 1. 在发送消息的页面(发送方)中,使用 JavaScript 调用 postMessage 方法发送消息。该方法接受两个参数:要发送的消息和接收消息的目标窗口的源(origin)。目标窗口的源可以是具体的名、协议和端口号,或者是通配符 "*" 表示任意源。 ```javascript var targetWindow = document.getElementById('target-frame').contentWindow; targetWindow.postMessage('Hello', 'https://target-domain.com'); ``` 2. 在接收消息的页面(接收方)中,监听 message 事件,通过 event.data 获取接收到的消息。在事件处理程序中可以对消息进行处理。 ```javascript window.addEventListener('message', function(event) { if (event.origin === 'https://source-domain.com') { console.log('Received message: ' + event.data); } }); ``` 通过这种方式,发送方和接收方可以进行通信,并且可以在消息中传递复杂的数据结构。但要注意,为了确保安全性,应该在接收方对来自不同源的消息进行验证,以防止恶意代码的攻击。 需要注意的是,postMessage 方法只能在现代浏览器中使用,兼容性可能会有所差异。此外,在使用 postMessage 进行通信时,也需要确保目标窗口(接收方)支持 postMessage 方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值