• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bencalie
博客园    首页    新随笔    联系   管理    订阅  订阅
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
posted on 2012-02-08 18:12  bencalie  阅读(2941)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3