JavaScript Javascript 跨子域通讯

hooopo for Shopper+ · December 16, 2012 · Last by aisensiy replied at March 10, 2013 · 5639 hits
Topic has been selected as the excellent topic by the admin.

跨域方法很多,像 JSONP、Iframe Hash Transport、HTML5 postMessage 甚至是 window.name。

但这些方法各有各的局限性,比如 JSONP 和 Iframe Hash Transport 受 URL 长度限制,本质还是同步请求。postMessage 受浏览器兼容性限制,当然还有 easyXDM 这东西,但是感觉太重。

最近项目里需要跨(子)域发送一个段长文本,上面到方案都有些局限,而需求还有一些特殊性,就是只需要跨子域。于是找到了设置document.domain这种方式。

这里需要说明的一点是,设置document.domain这种跨子域通讯的方式,不是说子域与子域之间可以发送 AJAX 请求,而是利用子域与子域的 iframe 之间可以传送数据这一特性完成跨域通讯。

这里是 demo 地址:http://subdomain1.herokuapp.com/ 源码:https://github.com/hooopo/cross_subdomain_demo

refs:

JSONP 可以是异步的啊,<script async src="..."> 就可以了,不过 IE 10 这个属性才有效果...

#2 楼 @knwang 这个用起来更复杂了吧 有兼容性限制?

#1 楼 @luikore 即使在 chrome 下,async 属性和普通异步请求也有差异。我前些天测试发现即使加 async 属性的 js 资源还会堵塞 onload 事件

#5 楼 @bhuztez 那还不错呢。github 这么用的。他们不支持 ie67

#8 楼 @hooopo 不客气,我还没来得及玩这个,如果你决定用这个了回来给我们分享下吧

#11 楼 @bhuztez

5. No authentication or cookies will be sent with the request

In order to prevent misuse of the user’s ambient authority (e.g. cookies, HTTP credentials, client certificates, etc), the request will be stripped of cookies and credentials and will ignore any authentication challenges or Set-Cookie directives in the HTTP response. XDomainRequests will not be sent on previously-authenticated connections, because some Windows authentication protocols  (e.g. NTLM/Kerberos) are per-connection-based rather than per-request-based.

Sites that wish to perform authentication of the user for cross-origin requests can use explicit methods (e.g. tokens in the POST body or URL) to pass this authentication information without risking the user’s ambient authority.

这一点就不太适合吧 ---update-- 没看明白,这东西是在认证的那个请求不发送 cookie 还是所有请求都不能发送?

http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

server 能控制的话 cors 也就是加些 headers 的事

#13 楼 @doitian 最主要的是 IE10 才正式支持 CORS

"不是说子域与子域之间可以发送 AJAX 请求,而是利用子域与子域的 iframe 之间可以传送数据这一特性完成跨域通讯。" 受教了,我之前尝试改成同域然后 ajax 失败以为是这种方法行不通了呢。

You need to Sign in before reply, if you don't have an account, please Sign up first.