跨域问题

跨域原因:同源策略一、

跨域出现的情况: 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中的代码:

 

b.com/index.html中的代码:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值