众所周知,对于同主域的多个子域名,可以通过设置 document.domain 来绕过同源策略(安全性极差,强烈反对这么做)
在我们的 JS 程序里,需要创建一个空白的 iframe(src="about:blank") 来做数据代理。
如果没有设置过 document.domain,这个 iframe 是可以随意访问的,没有问题。
但我们的 JS 程序部署在第三方页面,是否设置了 document.domain 是未知的,IE下只要设置了 document.domain,访问这个 iframe 就会提示“没有权限”了。(Firefox 和 Chrome 等非 IE 浏览器,都是没有这个问题的。)
所以,需要检测一下页面是否设置了 document.domain,并修复这个问题。
对于 test.weibo.com 设置 document.domain = "weibo.com"; 的情况,应该是很好判断了,只需判断 document.domain 和 window.location.host 是否相等即可。
但,如果是 test.weibo.com 设置 document.domain = "test.weibo.com"; 的就麻烦了。(各位看官,不要以为没人这样子做,谁知道呢)
解决的办法如下: 如果是 IE,就试着取一下 iframe 的 document 属性,如果 try catch 捕获到异常,就表示 A 页面设置了 document.domain,做一下修正。
document.domain = 'weibo.com'; var ifm = document.createElement('iframe'); ifm.src = "about:blank"; document.body.appendChild(ifm); if(/msie/i.test(navigator.userAgent)){ try{ ifm.contentWindow.document.title; }catch(e){ addEvent(ifm, "load", function () { alert(ifm.contentWindow.document.body.innerHTML); ifm.onload = null; }); ifm.src = "javascript:void((function(){var d=document;d.open();d.domain='"+ document.domain + "';d.write('111111111');d.close()})())"; } }
同步发表在:http://ming.sinaapp.com/?p=186