方法一:
window.name 跨域:
原理:
name 在浏览器环境中是一个全局window对象的属性,在一个窗口中赋了window.name之后,无论怎么刷新该窗口其window.name属性都不会变。但window.name 属性仅对相同域名的 iframe 可访问。
因此我们可以在异域目标页面将要获取的数据赋值给window.name ,此时对该窗口进行换域,换成本域url,此时本域即可访问赋值的window.name值
实例:
//异域页面赋值:www.ueditor.com
window.name='';
function select_list(modelid, id) {
var modeid = modelid + 'n' + id;
var result = window.name;
if(result =='' ) {
window.name = modeid;
}
}
//本域对异域进行换域并取值
//proxy_url 相当于代理页面,可以为空文件,放在本域任意目录下即可
var proxy_url = 'http://www.baidu.com/wzlist_example/proxy.html';
//换域
iframe.src = proxy_url;
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
//取值
result = iframe.contentWindow.name;
});
} else {
iframe.onload = function(){
取值
result = iframe.contentWindow.name;
};
}
window.name 的优势:
数据量更大(2M)
更安全
可传递多种数据格式
可跨所有域,主域、子域均可跨
window.name 的劣势:
只适用于隐藏iframe的情形(因中间过程需要换域,若换域后iframe仍显示则页面发生了变化,不在是原来页面)
方法二:
document.domain跨域:
document.domain方式只能跨主域相同的页面
主域相同的页面只要 document.domain 相同即可互相访问
a页面:
a.html (http://a.xxx.com/js/crossdomain/demo/a.htm)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A</title>
</head>
<body>
<textarea id="message">这是高层的密码!</textarea><br/>
<button id="test">看看员工在说什么</button><br/><br/><br/>员工们:<br/>
<iframe src="http://b.xxx.com/js/crossdomain/demo/b.htm" width="500" height="300" id="iframe"></iframe>
<script>
document.domain = "jiaju.com";
document.getElementByI d("test").onclick = function(){
alert(document.getElementByI d("iframe").contentWindow.document.getElementByI d("message").value);
}
</script>
</body>
</html>
b页面
b.html ((http://b.xxx.com/com/js/crossdomain/demo/b.htm ))
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSONP方式</title>
<script type="text/javascript" src="/js/jquery-1.5.1.min.js"></script>
</head>
<body>
<textarea id="message">这是员工的密码!</textarea><br/>
<button id="test">看看领导在说什么</button><br/>
<script>
document.domain = "jiaju.com";
document.getElementByI d("test").onclick = function(){
alert(parent.document.getElementByI d("message").value);
}
</script>
</body>
</html>
两个域都设置:document.domain=‘jiaju.com’