postMessage()
这些问题都有一些解决办法,但html5引入的message的API可以更方便、有效、安全的解决这些难题。postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
postMessage(data,origin)方法接受两个参数
1.data:要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果。
2.origin:字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为”*”,这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为”/”。
复制代码
<div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;"><div id="color">Frame Color</div></div><div><iframe id="child" src="http://lsLib.com/lsLib.html"></iframe></div>
复制代码
我们可以在http://test.com/index.html通过postMessage()方法向跨域的iframe页面http://lsLib.com/lsLib.html传递消息
window.onload=function(){
window.frames[0].postMessage('getcolor','http://lslib.com');//window.frames[0]是在下面
}
接收消息
test.com上面的页面向lslib.com发送了消息,那么在lslib.com页面上如何接收消息呢,监听window的message事件就可以
window.addEventListener(‘message’,function(e){
if(e.source!=window.parent) return;
var color=container.style.backgroundColor;
window.parent.postMessage(color,’*’);
},false);
来源: http://www.cnblogs.com/dolphinX/p/3464056.html
frames 属性返回窗口中所有命名的框架。
该集合是 Window 对象的数组,每个 Window 对象在窗口中含有一个框架或 >。属性 frames.length 存放数组 frames[] 中含有的元素个数。注意,frames[] 数组中引用的框架可能还包括框架,它们自己也具有 frames[] 数组。 <br/> 提示: 使用 frames.length 来获取框架的数量。 <br/> 语法 <br/> window.frames
浏览器支持
Internet ExplorerFirefoxOperaGoogle ChromeSafari
所有主要浏览器都支持 frames 属性
实例
实例
在页面中查找所有框架的数量,然后修改frame元素的src属性为 “w3cschool.cc”:
<html>
<body>
<iframe src="http://microsoft.com"></iframe>
<iframe src="http://google.com"></iframe>
<iframe src="http://youtube.com"></iframe>
<script>
for (var i=0; i<frames.length; i++)
{
frames[i].location="http://w3cschool.cc"
}
</script>
</body>
</html>