IE 判断是否设置 document.domain

众所周知,对于同主域的多个子域名,可以通过设置 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

转载于:https://www.cnblogs.com/bencalie/archive/2012/02/08/ie_detect_document_domain.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值