iframe + postMessage跨域通信

2020-12-21 14:00:19

参考地址 使用 iframe + postMessage 实现跨域通信

在实际项目开发中可能会碰到在 a.com 页面中嵌套 b.com 页面,这时第一反应是使用 iframe,但是产品又提出在 a.com 中操作,b.com 中进行显示,或者相反。

1、postMessage

  postMessage方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

语法:

otherWindow.postMessage(message, targetOrigin, [transfer]);1
  • otherWindow:其他窗口的引用,如 iframe的contentWindow、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。

  • message:将要发送到其他window的数据。

  • targetOrigin:指定那些窗口能接收到消息事件,其值可以是字符串 “*” 表示无限制,或者是一个URI。

  • transfer:是一串和message同时传递的Transferable对象,这些对象的所有权将被转移给消息的接收方,而发送方将不再保留所有权。

postMessage方法被调用时,会在所有页面脚本执行完毕之后像目标窗口派发一个 MessageEvent 消息,该MessageEvent消息有四个属性需要注意:

  • type:表示该message的类型

  • data:为 postMessage 的第一个参数

  • origin:表示调用postMessage方法窗口的源

  • source:记录调用postMessage方法的窗口对象

2、搭建框架

main.html

<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage 跨域通信 主页面</title>
</head>
<body>
    <h1>主页面</h1>
    <iframe id="child" src="http://b.com/iframepage.html"></iframe>
    <div>
        <h2>主页面接收消息区域</h2>
        <span id="message"></span>
    </div>
</body> 
</html>123456789101112131415

iframepage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage跨域通信 子页面</title>
</head>
<body>
    <h2>子页面</h2>
    <div>
        <h3>接收消息区域</h3>
        <span id="message"></span>
    </div>
</body>
</html>1234567891011121314

2、父向子发送消息

main.html

<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("主页面消息", 
                "http://b.com/iframepage.html")
    }
</script>1234567

注意:一定是页面加载完成后在发送消息,否则会因为 iframe 未加载完成报错。

Failed to execute ‘postMessage’ on ‘DOMWindow’1

子页面接收消息:
iframepage.html

<script>
    window.addEventListener('message',function(event){
        console.log(event);
        document.getElementById('message').innerHTML = "收到" 
            + event.origin + "消息:" + event.data;
    }, false);
</script>1234567

此时可看到页面中,iframe的子页面中打印了

收到http://a.com消息:主页面消息1


主向子发送消息


以及控制台打印了MessageEvent对象。


MessageEvent对象


3、子向父发送消息

子页收到消息后回复父页面
iframepage.html

<script>
    window.addEventListener('message',function(event){
        console.log(event);
        document.getElementById('message').innerHTML = "收到" 
            + event.origin + "消息:" + event.data;
        top.postMessage("子页面消息收到", 'http://a.com/main.html')
    }, false);
</script>12345678

父页面收到消息并显示:

window.addEventListener('message', function(event){
    document.getElementById('message').innerHTML = "收到" 
        + event.origin + "消息:" + event.data;
}, false);1234


子向父发送消息


4、完整代码

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage 跨域通信 主页面</title>
</head>
<body>
    <h1>主页面</h1>
    <iframe id="child" src="http://b.com/iframepage.html"></iframe>
    <div>
        <h2>主页面接收消息区域</h2>
        <span id="message"></span>
    </div>
</body> 
<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("主页面消息", 
            "http://b.com/iframepage.html")
    }
    window.addEventListener('message', function(event){
        document.getElementById('message').innerHTML = "收到"
         + event.origin + "消息:" + event.data;
    }, false);
</script>
</html>1234567891011121314151617181920212223242526

iframepage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage跨域通信 子页面</title>
</head>
<body>
    <h2>子页面</h2>
    <div>
        <h3>接收消息区域</h3>
        <span id="message"></span>
    </div>
</body>
<script>
    window.addEventListener('message',function(event){
        if(window.parent !== event.source){return}
        console.log(event);
        document.getElementById('message').innerHTML = "收到" 
            + event.origin + "消息:" + event.data;
        top.postMessage("子页面消息收到", 'http://a.com/main.html')
    }, false);
</script>
</html>


  • 2019-05-27 10:43:34

    IntelliJ IDEA中C盘文件过大怎么办

    当我在D:\ 安装完IDEA9.0之后,建立了一个工程,发现C:\Users\Administrator\.IntelliJIdea90 竟然增大到了500+M,并且随着使用在逐渐增大,这样占用系统盘资源是非常让人不爽的,那么如何将其修改到其他路径呢?

  • 2019-05-28 13:33:20

    BRVAH+MTRVA,复杂?不存在的

    言归正传,这样的一个首页,我们需要做怎么样的基础工作呢?或者说,碰到以后更复杂的页面我们应该怎么做?这里小提示下,不要再用什么类似ScrollView的这种东西了,诶,好像说的有点绝对,尽量不要用,这不是谷歌想要看到的,5.0谷歌推出了RecyclerView,从它的整个设计架构来看,简直就是为这而生的。而RecyclerView的视图是通过Adapter来渲染的。原始的Adapter,让人很蛋疼,重复工作太多,我们应该要有封装的思想,把最需要的部分提供出来,其它不用管。

  • 2019-05-29 14:19:19

    解决Git中fatal: refusing to merge unrelated histories

    Git的报错 在使用Git的过程中有时会出现一些问题,那么在解决了每个问题的时候,都需要去总结记录下来,下次不再犯。 一、fatal: refusing to merge unrelated histories 今天在使用Git创建项目的时候,在两个分支合并的时候,出现了下面的这个错误。

  • 2019-05-29 15:47:51

    撤销commit

    在git push的时候,有时候我们会想办法撤销git commit的内容