跨域原因:同源策略一、
跨域出现的情况: URL 说明 是否允许通信
http://www.a.com/a.js
http://www.a.com/b.js 同一域名下 允许
http://www.a.com/lab/a.
jshttp://www.a.com/script/b.js 同一域名下不同文件夹 允许
1:http://www.a.com:8000/a.js
http://www.a.com/b.js同一域名,不同端口 不允许
2:http://www.a.com/a.js
https://www.a.com/b.js 同一域名,不同协议 不允许
:http://www.a.com/a.js
http://70.32.92.74/b.js 域名和域名对应ip 不允许
4:http://www.a.com/a.js
http://script.a.com/b.js 主域相同,子域不同 不允许
5:http://www.a.com/a.js
http://a.com/b.js 同一域名,不同二级域名(同上) 不允许(cookie这种情况下也不允许访问)
6:http://www.cnblogs.com/a.js
http://www.a.com/b.js 不同域名
二、跨域解决方案:document.domain 、 jsonp 、 iframe
对于第4种情况对于主域相同而子域不同的例子,
可以通过设置document.domain的办法来解决www.a.com上的a.htmlXHTMLdocument.domain = 'a.com';var ifr = document.createElement('iframe');ifr.src = 'http://script.a.com/b.html';ifr.style.display = 'none';document.body.appendChild(ifr);ifr.onload = function(){ var doc = ifr.contentDocument || ifr.contentWindow.document; // 在这里操纵b.html alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);};document.domain = 'a.com';var ifr = document.createElement('iframe');ifr.src = 'http://script.a.com/b.html';ifr.style.display = 'none';document.body.appendChild(ifr);ifr.onload = function(){ var doc = ifr.contentDocument || ifr.contentWindow.document; // 在这里操纵b.html alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);};
1、安全性,当一个站点(b.a.com)被攻击后,另一个站点(c.a.com)会引起安全漏洞。
2、如果一个页面中引入多个iframe,要想能够操作所有iframe,必须都得设置相同domain。script.a.com上的b.htmlXHTMLdocument.domain = 'a.com';1document.domain = 'a.com';
二、通过动态创建script
四 通过window.name实现跨域
http://www.cnblogs.com/rainman/archive/2011/02/21/1960044.html
五、通过wobsocket.postmessage()
5、使用HTML5 postMessage
HTML5中最酷的新功能之一就是 跨文档消息传输Cross Document Messaging。 下一代浏览器都将支持这个功能:Chrome 2.0+、Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, 和 Safari 4.0+ 。 Facebook已经使用了这个功能,用postMessage支持基于web的实时消息传递。
-
otherWindow.postMessage(message, targetOrigin);
-
otherWindow: 对接收信息页面的window的引用。可以是页面中iframe的contentWindow属性;
window.open的返回值;通过name或下标从
window.frames取到的值。
message: 所要发送的数据,string类型。
targetOrigin: 用于限制otherWindow,“*”表示不作限制
a.com/index.html中的代码:
1
2
3
4
5
6
7
8
9
|
<iframe
id
=
"ifr"
src
=
"b.com/index.html"
>
</iframe>
<script
type
=
"text/javascript"
>
window
.
onload
=
function
(
)
{
var
ifr
=
document
.
getElementById
(
'ifr'
)
;
var
targetOrigin
=
'http://b.com'
;
// 若写成'http://b.com/c/proxy.html'效果一样
// 若写成'http://c.com'就不会执行postMessage了
ifr
.
contentWindow
.
postMessage
(
'I was there!'
,
targetOrigin
)
;
}
;
</script>
|
b.com/index.html中的代码:
1
2
3
4
5
6
7
8
9
10
|
<script
type
=
"text/javascript"
>
window
.
addEventListener
(
'message'
,
function
(
event
)
{
// 通过origin属性判断消息来源地址
if
(
event
.
origin
==
'http://a.com'
)
{
alert
(
event
.
data
)
;
// 弹出"I was there!"
alert
(
event
.
source
)
;
// 对a.com、index.html中window对象的引用
// 但由于同源策略,这里event.source不可以访问window对象
}
}
,
false
)
;
</script>
|