vapour's blog

19Apr/12Off

跨域之window.postMessage

window.postMessage是一种跨域交互方法,支持通过iframe和window.open页面之间的跨域通信。经测试IE7+、Firefox、Opera、Chrome、Safari均支持window.postMessage。

vapour.net/message.htm:

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>window.postMessage</title>
</head>

<body>
<iframe id="ifrBlog" src="http://vapour.cn/iframe.htm"></iframe>

<script type="text/javascript">
(function (){
    var ifr = document.getElementById('ifrBlog').contentWindow;
    
    window.onload = function(){
        ifr.postMessage('Hello, I am vapour, from vapour.net', 'http://vapour.cn');
    };
   
    if (window.addEventListener) {
        window.addEventListener('message', function(ev){
            alert(ev.data);
            //console.log(ev.data, ev.origin, ev.source);
        }, false);
    } else {
        window.attachEvent('onmessage', function(ev){
            alert(ev.data);
            //console.log(ev.data, ev.origin, ev.source);
        });
    }
    
})();
</script>
</body>
</html>

 

vapour.cn/iframe.htm:

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>window.postMessage</title>
</head>

<body>
<script type="text/javascript">
(function (){
    if (window.addEventListener) {
        window.addEventListener('message', function(ev){
            alert(ev.data);
            //console.log(ev.data, ev.origin, ev.source);
            ev.source.postMessage('Hi, this is vapour.cn', 'http://vapour.net');
        }, false);
    } else {
        window.attachEvent('onmessage', function(ev){
            alert(ev.data);
            //console.log(ev.data, ev.origin, ev.source);
            ev.source.postMessage('Hi, this is vapour.cn', 'http://vapour.net');
        });
    }
})();
</script>
</body>
</html>

 

参考:

22Jul/11Off

ie中的跨域和ckeditor

在IE中修改了document.domain进行提权后(无论修改前后域名是否不同),iframe都会出现跨域问题。

ckeditor中检查跨域的代码,是根据判断document.domain和window.location.hostname是否相同来来判断跨域的。

isCustomDomain: function () {
   if (!this.ie) return false;
   var g = document.domain,
   h = window.location.hostname;
   return g != h && g != '[' + h + ']';
}

当我们执行在页面执行 document.domain = document.domain 后,执行 isCustomDomain 会返回false,这时ie会因为跨域,报拒绝访问的错误。

所以当我们,在修改document.domain时要进行判断,当新域和旧域不同时再修改document.domain

var oldDomain = document.domain,
    newDomain = 'xxx.com';
if (newDomain != oldDomain) {
   document.domain = newDomain;
}