同源策略限制:
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说阅读私密邮件,发送虚假邮件,查看聊天记录等等。所谓同源是指,协议,域名,端口相同。三者只有有一个不相同,就认为不同源!
例如:域:http://store.company.com/dir/index.html
- 协议不同:https://store.company.com/dir/index.html
- 端口不同:http://store.company.com:81/dir/index.html
- 主机名不同:http://news.company.com/dir/index.html
跨域请求:
1. 对于主域相同而子域不同的例子,可以通过设置document.domain的办法来解决。
ajax不允许跨子域请求,但是iframe可以!可以通过提升域的方法来实现。
例如www.a.com/a.html和a.com/b.html为例,只需在a.html中添加一个b.html的iframe,并且设置两个页面的document.domain都为’a.com’(只能为主域名),两个页面之间即可互相访问了。
如果b.html要访问a.html,可在子窗口(iframe)中通过window.parent来访问父窗口的window对象。
例如www.a.com/a.html中的script:
document.domain='a.com';//提升域
varifr = document.createElement('iframe');
ifr.src = 'http://a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
//获取iframe的document对象
//W3C的标准方法是iframe.contentDocument,
//IE6、7可以使用document.frames[ID].document
//为了更好兼容,可先获取iframe的window对象iframe.contentWindow
vardoc = ifr.contentDocument || ifr.contentWindow.document;
// 在这里操纵b.html
alert(doc.getElementById("test").innerHTML);
而a.com/b.html:
<!DOCTYPE >
<html>
<head>
<title></title>
<scripttype="text/javascript">
document.domain='a.com';//提升域
</script>
</head>
<body>
<h1id="test">Hello World</h1>
</body>
</html>