首页 技术 正文
技术 2022年11月21日
0 收藏 507 点赞 2,310 浏览 1499 个字

一、postMessage

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机(两个页面的模数 Document.domain设置为相同的值)时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

调用 postMessage() 方法时,向目标窗口派发一个 Event 消息。 该 Event 消息的 data 属性为 postMessage() 的数据;origin 属性表示调用 postMessage() 方法的页面的地址。

二、语法

otherWindow.postMessage(message, targetOrigin)

说明

  • otherWindow:其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
  • message:将要发送到其他 window 的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。
  • targetOrigin:通过窗口的 origin 属性来指定哪些窗口能接收到消息事件,其值可以是字符串 * (表示无限制)或者一个 URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。

三、示例

我配了两个域名 example.mazey.cnexample0.mazey.cn,其中 http://example0.mazey.cn/post-message/send.html 会给 http://example.mazey.cn/post-message/receive.html 发送一条消息 Message From Mazey.

send.html

<script>
window.onload = function () {
window.parent.postMessage(
'Message From Mazey.',
'*'
)
}
</script>

receive.html

<script>
// 监听
window.addEventListener(
'message',
event => {
let origin = event.origin || event.originalEvent.origin
console.log(event, origin, event.data) // MessageEvent{...} "http://example0.mazey.cn" "Message From Mazey."
}
)
// 使用 JS 加载 iframe,保证监听创建后再加载 iframe。
let iframeEle = document.createElement('iframe')
iframeEle.src = 'http://example0.mazey.cn/post-message/send.html'
iframeEle.style = 'border: none;width: 0;height: 0;'
document.body.insertBefore(iframeEle, document.body.firstChild)
</script>

注意

如果发送的消息有敏感信息(例如:密码),始终验证接受时的 event.origin 和指定发送时的 targetOrigin。

上一篇: authz_core_module
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,909
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,434
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,249
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,060
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,692
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,730