首页 > 代码库 > 关于同源策略的总结:

关于同源策略的总结:

如何引用: (iFrame指的是iframe DOM节点)
1. 引用iframe的window对象:iFrame.contentWindow
2. 引用iframe的document对象:iFrame.contentDocument,或者:iFrame.contentWindow.document

 

示例:

两个页面,前者页面中嵌入iframe,src指向后者:
1. test.nuomi.com/link1.vm
2. nuomi.com/link2.vm;

 

同源要求:Protocols, domains, and ports均相同
子域名不同的两个站:test.nuomi.com, nuomi.com,如果要通信,必须设置为统一的域名:document.domain=nuomi.com;
即使其中一个已经是域名:nuomi.com,仍然需要明确调用:document.domain=nuomi.com;

 

document.domain设值:
1. 只能是当前域名的suffix,否则报错:Uncaught SecurityError: Failed to set the ‘domain‘ property on ‘Document‘: ‘test‘ is not a suffix of ‘test.nuomi.com‘.
2. 设值为com也会报错:‘com‘ is a top-level domain.
3. 必须是"."点分隔的后缀,否则报错:‘mi.com‘ is not a suffix of ‘test.nuomi.com‘

 

不同源时:

1. 外面访问里面window的document属性:iFrame.contentDocument
Chrome报错:  Uncaught SecurityError: ... Protocols, domains, and ports must match.
Firefox报错:   null
IE9报错:      SCRIPT5: 拒绝访问

2. 里面访问外面window的document属性:window.parent.document
Chrome报错:  Uncaught SecurityError: ... Protocols, domains, and ports must match.
Firefox报错:   Permission denied to access property ‘document‘
IE9报错:    SCRIPT5: 拒绝访问

 

解决方案:

1. 都属于同一个域名,但子域不同时,都设置document.domain;即可相互访问;

2. postMessage解决跨域问题,支持IE9及以上;

/* 外面页面的script */function msgHandler(e){  console.log("Outer message:", e);}if(window.addEventListener){  window.addEventListener("message", msgHandler, false);}else{  window.attachEvent("message", msgHandler);}// 待加载后发送$("#iframe1").on("load", function(e){  console.info("Iframe onl oad:", e);  $("#iframe1")[0].contentWindow.postMessage("Data from outer, repects ‘the structured clone algorithm. ‘", "*");});
 1 /* 里面页面的script */ 2 function msgHandler(e){ 3     console.log("Inner message:", e); 4 } 5  6 if(window.addEventListener){ 7     window.addEventListener("message", msgHandler, false); 8 }else{ 9     window.attachEvent("message", msgHandler);10 }11 window.parent.postMessage("Data from inner to outer.", "*");

 

  

 

 

 

参考资料:

1. Same-origin policy      https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Changing_origin

2. document.domain       https://developer.mozilla.org/en-US/docs/Web/API/document.domain

3. HTML <iframe> Element   https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

4. window.postMessage    https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage 

 

关于同源策略的总结: