window.postMessage()方法可以安全地实现Window对象之间的跨域通信。例如,在页面和嵌入其中的iframe之间。

不同页面上的脚本允许彼此访问,当且仅当它们源自的页面共享相同的协议,端口号和主机(也称为“同源策略”)。window.postMessage()提供了一个受控的机制相对来安全地规避这个限制。

发送消息的基本语法:

targetWindow.postMessage(message, targetOrigin, [transfer]);

targetWindow就是接收消息的窗口的引用。 获得该引用的方法包括:

  • Window.open
  • Window.opener
  • HTMLIFrameElement.contentWindow
  • Window.parent
  • Window.frames +索引值

message就是要发送到目标窗口的消息。 数据使用结构化克隆算法进行序列化。 这意味着我们可以将各种各样的数据对象安全地传递到目标窗口,而无需自己对其进行序列化。

targetOrigin就是指定目标窗口的来源,必须与消息发送目标相一致,可以是字符串“*”或URI。 *表示任何目标窗口都可接收,为安全起见,请一定要明确提定接收方的URI。

transfer是可选参数

接收端:

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
if (event.origin !== "http://127.0.0.1:3808/")
return;
}
 
event对象有三个属性,分别是origin,data和source。event.data表示接收到的消息;event.origin表示postMessage的发送来源,包括协议,域名和端口;event.source表示发送消息的窗口对象的引用; 我们可以用这个引用来建立两个不同来源的窗口之间的双向通信。

完整示例:

1、父页面

  <title>father</title>
</head>
<body>
<div style="width: 200px;float: left;margin-right: 200px;border: 1px solid #333;">
<div id="color"> frame color</div>
</div>
<div>
<iframe id="child" src="http://127.0.0.1:3808/iframe-son/index.html"></iframe>
</div>
<script>
window.onload = function() {
// 初始化div颜色
window.frames[0].postMessage('getcolor', 'http://127.0.0.1:3808/');
} window.addEventListener('message',function(e) {
// 监听子页面颜色的改变即发送的消息,设置div颜色
var color = e.data;
document.getElementById('color').style.backgroundColor = color;
},false)
</script>
</body>
</html>

2、子页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>son</title>
</head>
<body>
<div id="container" onclick="changeColor();" style="width: 100%; height: 100%;background-color: rgb(204,102,0)">
click to change color
</div> <script>
var container = document.getElementById('container'); //监听父页面传递过来的信息
window.addEventListener('message', function (e) {
if(e.source != window.parent) return ;
// container.innerHTML = e.data var color = container.style.backgroundColor;
window.parent.postMessage(color,'*');
},false) //改变颜色的方法
function changeColor() {
var color = container.style.backgroundColor;
if(color=='rgb(204, 102, 0)'){
color='rgb(204, 204, 0)';
}else{
color='rgb(204,102,0)';
}
container.style.backgroundColor = color;
// 给父元素发送消息
window.parent.postMessage(color,'*');
}
</script>
</body>
</html>

window.postMessage()实现(iframe嵌套页面)跨域消息传递的更多相关文章

  1. iframe嵌套页面 跨域

    父级调用iframe方法: document.getElementById("iframe").contentWindow.func(data1,data2...) 子级 ifra ...

  2. window.postMessage 在iframe父子页面数据传输

    介绍 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage window.postMessage 发送方 接收方 示例 ...

  3. window.postMessage()实现跨域消息传递

    window.postMessage() 方法可以安全地实现跨源通信.通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https), 端口号(443为https的默认值), ...

  4. easyui 中iframe嵌套页面,大弹窗自适应居中的解决方法。$('#win').window()

    easyui 中iframe嵌套页面,大弹窗自适应居中的解决方法.$('#win').window() 以下是左边栏和头部外层遮罩显示和隐藏方法 /*外层 遮罩显示*/ function wrapMa ...

  5. window.opener方法的使用 js跨域

    原文:window.opener方法的使用 js跨域 最近公司网站登陆加入了第三方登陆.可以用QQ直接登陆到我们网站,在login页面A中点QQ登陆时,调用了一个window.open文件打开一个lo ...

  6. 通过Html5的postMessage和onMessage方法实现跨域跨文档请求访问

    在项目中有应用到不同的子项目,通过不同的二级域名实现相互调用功能.其中一个功能是将播放器作为单独的二级域名的请求接口,其他项目必须根据该二级域名调用播放器.最近需要实现视频播放完毕后的事件触发,调用父 ...

  7. easyui 中iframe嵌套页面,提示弹窗遮罩的解决方法,parent.$.messager.alert和parent.$.messager.confirm

    项目中用到easyui 布局,用到north,west,center三个区域,且在center中间区域嵌入iframe标签.在主内容区做一些小提示弹窗(例如删除前的弹窗提示确认)时,会遇到遮罩问题,由 ...

  8. 解决Iframe跨域高度自适应,利用window.postMessage()实现跨域消息传递页面高度(JavaScript)

    在iframe跨域引用高度自适应这块写的js方式都试了不管用,最终使用的是window.postMessage() 跨域获取高度 传递信息 1.首先,在主页面上使用iframe引入子页面:也就是A.h ...

  9. iframe中涉及父子页面跨域问题

    什么是跨域? 跨域,指的是浏览器不能执行其他网站的脚本.它是由浏览器的同源策略造成的,是浏览器施加的安全限制.所谓同源是指相同的域名.协议和端口,只要其中一项不同就为跨域. 举几个例子: http:/ ...

随机推荐

  1. openresty开发系列10--openresty的简单介绍及安装

    openresty开发系列10--openresty的简单介绍及安装 一.Nginx优点 十几年前,互联网没有这么火,软件外包开发,信息化建设,帮助企业做无纸化办公,收银系统,工厂erp,c/s架构偏 ...

  2. ISO/IEC 9899:2011 条款6.9.1——函数定义

    6.9.1 函数定义 语法 1.function-definition: declaration-specifiers    declarator    declaration-listopt     ...

  3. Spring cloud微服务安全实战-3-14章节小结

    认证:一个httpBasic 一个是用户名密码的认证 授权:数据库内判断的r就是读 w就是写 ,ACL 获取用户信息的这段逻辑,实际上着也是安全机制的一种.防止越权,当前只能看到自己的信息. Spri ...

  4. 123457123457#0#----com.MC.3or1KongLongPT867----前拼后广--3or1恐龙PtGame-mc

    com.MC.3or1KongLongPT867----前拼后广--3or1恐龙PtGame-mc

  5. PAT 甲级 1146 Topological Order (25 分)(拓扑较简单,保存入度数和出度的节点即可)

    1146 Topological Order (25 分)   This is a problem given in the Graduate Entrance Exam in 2018: Which ...

  6. lombok插件/slf4j中字符串格式化

    大家在编写springboot项目的过程中可能会接触到lombok这个插件,这个插件可以在编译时帮我生成很多代码. 1.@Data生成Getter和Setter代码,用于类名注释 2.@Getter ...

  7. Python - Django - request 对象

    request.method: 获取请求的方法,例如 GET.POST 等 views.py: from django.shortcuts import render, HttpResponse # ...

  8. 【Leetcode_easy】849. Maximize Distance to Closest Person

    problem 849. Maximize Distance to Closest Person solution1: class Solution { public: int maxDistToCl ...

  9. Nginx配置文件的反向代理

    问题描述:项目需要预览pdf,前端控件支持的格式是http://192.168.0.1/pdf/a.pdf  是这样的,然后我就想给路径配个nginx反向代理就好了,但是配置的时候出问题了. 1.正确 ...

  10. Python之可变参数,*参数,**参数,以及传入*参数,进行解包

    1.定义了一个需要两个参数的函数 def print_str(first, second): print first print second if __name__ == "__main_ ...