浏览器的同源策略:
1.协议相同
2.域名相同
3.端口相同
如果三者有一个不相同,就会造成跨域;阮一峰老师在文中曾提到过;如果不是同源,就会:
Cookie,localStorage,IndexDB将不可以获取到.
Dom无法获取.
ajax请求失败.
我们可以使用以下几种方法:
1.iframe+window.domain
如果有两个不同源的页面,例如:a.test.com 和 b.test.com;
我们在两个页面可以设置
document.domain="test.com";
然后我们可以使用页面window下的方法实现了共享.
如果我们在a下面定义了一个:
document.A=function(){
console.log('i am contentA');
};
那么在b中:
我们调用document.A();//i am contentA;
我们使用这个方法在a页面调用b的cookie.
2.iframe+window.name
window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,
窗口载入的所有的页面都是共享一个window.name的,
每个页面对window.name都有读写的权限。(window.name的值只能是字符串的形式,这个字符串的大小最大能允许2M左右甚至更大的一个容量,具体取决于不同的浏览器,一般够用了。)
如果有两个不同源的页面,例如:a.test.com 和 b.test.com;
在a中:
我们如果设置window.name="i am a.html";
在b中:
<iframe id="b" src="a.test.com" onload="test()"></iframe>
js:
function test(){ var obj = document.getElementById("iframe"); obj.onload = function(){ var msg = obj.contentWindow.name; console.log(msg); } obj.src = "b.test.com/b1.html"; }
设置一个空的b1页面接受;我们可以看见输出// i am a.html
3.iframe+window.postMessage()
html5炫酷的API之一:跨文档消息传输。高级浏览器Internet Explorer 8+, chrome,Firefox , Opera 和 Safari 都将支持这个功能。这个功能实现也非常简单主要包括接受信息的"message"事件和发送消息的"postMessage"方法。
发送消息的"postMessage"方法:
向外界窗口发送消息:
otherWindow.postMessage(message, targetOrigin);
otherWindow: 指目标窗口,也就是给哪个window发消息。
message: 要发送的消息,类型为 String、Object (IE8、9 不支持)
targetOrigin: 是限定消息接收范围,不限制请使用 '*'
如果有两个不同源的页面,例如:a.test.com 和 b.test.com;
在a的a.html中:
js:
window.onload=function(){
if(typeof window.postMessage===undefined){
alert('浏览器不支持window.postMessage')
}else{
window.top.postMessage({a:'i am a'},'b.test.com')
}
}
在b中:
html:
<iframe id="iframe" src="a.test.com/a.html" onload=""test()></iframe>
js:
function test(){
if(typeof window.postMessage===undefined){
alert('浏览器不支持window.postMessage')
}else{
window.addEventListener("message",function(e){
if(e.origin==="a.test.com"){
console.log(e.data)//{a:'i am a'}
}
},false)
}
}
4.jsonp跨域
jsonp是利用script标签可以跨域访问资源的特性,在页面内动态插入一个script标签,向服务器发起数据的跨域请求。服务器收到请求后,将数据放在一个指定名字的回调函数中传回;
function addScriptTag(src) {
var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } window.onload = function () { addScriptTag('http://example.com/ip?callback=foo'); } function foo(data) { console.log('Your public IP address is: ' + data.ip); };