侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

详解HTML5 window.postMessage与跨域

Windows  /  管理员 发布于 4年前   256

在前一篇文章中,讲到浏览器同源策略,即阻止不同域的页面间访问彼此的方法和属性,并对解决同源策略跨域问题提出的解决方案进行阐述:子域代理、JSONP、CORS。本篇将详细阐述HTML5 window.postMessage,借助postMessage API,文档间可以以安全可控的方式实现跨域通信,第三方JavaScript代码也可以与iframe内加载的外部文档进行通信。

HTML5 window.postMessage API

HTML5 window.postMessage是一个安全的、基于事件的消息API。

postMessage发送消息

在需要发送消息的源窗口调用postMessage方法即可发送消息。

源窗口

源窗口可以是全局的window对象,也可以是以下类型的窗口:

文档窗口中的iframe:  

var iframe = document.getElementById('my-iframe');    var win = iframe.documentWindow;

JavaScript打开的弹窗:  

var win = window.open();

当前文档窗口的父窗口:  

var win = window.parent;

打开当前文档的窗口:  

var win = window.opener();

找到源window对象后,即可调用postMessage API向目标窗口发送消息:

``win.postMessage('Hello', 'ttp://jhssdemo.duapp.com/');```

postMessage函数接收两个参数:第一个为将要发送的消息,第二个为源窗口的源。

注:只有当目标窗口的源与postMessage函数中传入的源参数值匹配时,才能接收到消息。

接收postMessage消息

要想接收到之前源窗口通过postMessage发出的消息,只需要在目标窗口注册message事件并绑定事件监听函数,就可以在函数参数中获取消息。

window.onload = function() {        var text = document.getElementById('txt');          function receiveMsg(e) {            console.log("Got a message!");            console.log("nMessage: " + e.data);            console.log("nOrigin: " + e.origin);            // console.log("Source: " + e.source);            text.innerHTML = "Got a message!<br>" +                "Message: " + e.data +                "<br>Origin: " + e.origin;        }        if (window.addEventListener) {            //为窗口注册message事件,并绑定监听函数            window.addEventListener('message', receiveMsg, false);        }else {            window.attachEvent('message', receiveMsg);        }    };

message事件监听函数接收一个参数,Event对象实例,该对象有三个属性:

  1. data 发送的具体消息
  2. origin 发送消息源
  3. source 发送消息窗口的window对象引用

说明

  1. 可以将postMessage函数第二个参数设为*,在发送跨域消息时会跳过对发送消息的源的检查。
  2. postMessage只能发送字符串信息。

实例

源窗口  

<!DOCTYPE html>    <html lang="en">    <head>        <meta charset="UTF-8">        <title>Html5 postMessage</title>        <style>            #otherWin {                width: 600px;                height: 400px;                background-color: #cccccc;            }        </style>    </head>    <body>        <button id="btn">open</button>        <button id="send">send</button>         <!-- 通过 iframe 嵌入子页面(接收消息目标窗口) -->          <iframe src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html"                      id="otherWin"></iframe>          <br/><br/>          <input type="text" id="message"><input type="button"                  value="Send to child.com" id="sendMessage" />         <script>            window.onload = function() {                var btn = document.getElementById('btn');                var btn_send = document.getElementById('send');                var sendBtn = document.getElementById('sendMessage');                var win;                btn.onclick = function() {                    //通过window.open打开接收消息目标窗口                    win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp');                }                btn_send.onclick = function() {                     // 通过 postMessage 向子窗口发送数据                          win.postMessage('Hello', 'http://jhssdemo.duapp.com/');                }                function sendIt(e){                     // 通过 postMessage 向子窗口发送数据                    document.getElementById("otherWin").contentWindow                     .postMessage(                         document.getElementById("message").value,                         "http://jhssdemo.duapp.com/");                 }                 sendBtn.onclick = function(e) {                    sendIt(e);                };            };        </script>    </body>    </html>

目标窗口win.html

<!DOCTYPE html>    <html lang="en">    <head>        <meta charset="UTF-8">        <title>Html5 postMessage</title>        <style>            #txt {                width: 500px;                height: 300px;                background-color: #cccccc;            }        </style>    </head>    <body>        <h1>The New Window</h1>        <div id="txt"></div>        <script>                    window.onload = function() {                var text = document.getElementById('txt');                  //监听函数,接收一个参数--Event事件对象                function receiveMsg(e) {                    console.log("Got a message!");                    console.log("nMessage: " + e.data);                    console.log("nOrigin: " + e.origin);                    text.innerHTML = "Got a message!<br>" +                        "Message: " + e.data +                        "<br>Origin: " + e.origin;                }                if (window.addEventListener) {                    //为window注册message事件并绑定监听函数                    window.addEventListener('message', receiveMsg, false);                }else {                    window.attachEvent('message', receiveMsg);                }            };        </script>    </body>    </html>

回顾

通过本篇的学习,了解了使用HTML5的postMessage API在窗口间进行通信,也知道可以借助其实现跨域通信;现代浏览器基本都支持postMessage,而对于一些老式浏览器如IE7-等,可以使用一定的替代方案,进行数据通信,如window.name、url查询字符和hash片段等。  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    php源码怎么在win运行
    下一条:
    详解window.open被浏览器拦截的解决方案
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Windows 10的告别:2025年10月14日,一段时代的终结(0个评论)
    • windows 11激活_Win11 KMS激活流程步骤(1个评论)
    • 安装Windows 11系统的注意了,看看你的cpu是否在微软兼容列表排除中(1个评论)
    • 微软将于2022年9月20日推送Windows11 22H2新版本,推测2024发布windows 12(0个评论)
    • windows11系统中可以关闭禁止的服务及介绍(1个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-01
    • 2018-06
    • 2020-06
    • 2021-06
    • 2021-07
    • 2022-01
    • 2022-04
    • 2022-08
    • 2023-08
    • 2023-10
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客