Javascript window.open“SCRIPT5:访问被拒绝”,因为子域名未加载

时间:2017-03-09 13:49:35

标签: javascript internet-explorer

IE9上下文中的两个Web应用程序设置:

  

david.mydomain.com

  

john.mydomain.com

大卫给约翰开了一个新窗口:

  

var popup = window.open('john.mydomain.com');

大卫想知道约翰何时会关闭,然后发送XHR。

完成:

  1. 像这样设置正确的事件(即https://msdn.microsoft.com/library/ms536907(v=vs.85).aspx) :
      

    john.attachEvent(“onbeforeunload”,willClose);

  2. 像这样在每个窗口中设置相同的域(即Cross-domain JavaScript code with sibling sub-domains):
      

    $(document).ready(function(){window.document.domain ='mydomain.com';}

  3. 并添加已发送的XHR(即https://www.w3schools.com/xml/tryit.asp?filename=try_dom_xmlhttprequest):
      

    new XMLHttpRequest()。open(“GET”,“welcome.png”,true).send();

  4. 我的代码最终看起来像:

    var willClose = function(e){
    		console.log('will close popup');
    		var xhttp = new XMLHttpRequest();
    		xhttp.onreadystatechange = function() {
    			if (this.readyState == 4 && this.status == 200) {
    				console.log('close xhr done');
    			}
    		};
    		xhttp.open("GET", "welcome.png", true);
    		xhttp.send();
    		return true ;
    	};
    
    $( document ).ready(function() {
    		
    		window.document.domain = 'mydomain.com';
    		
    		$('#popup').click(function() {
    			var win = window.open('http://john.mydomain.com/', '_blank');
    			
    			//KO : win.onbeforeunload = willClose;
    			//KO : win.addEventListener ("beforeunload", willClose);
          win.attachEvent("onbeforeunload", willClose);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <button id="popup">Open pop up in sub domain</button>

    问题:

    我仍然有一个IE跨域异常:'SCRIPT5:拒绝访问' 1)john.attachEvent(“onbeforeunload”,willClose); 为什么?

    (optionnal)感谢为所有浏览器优化这个js(IE9会死)

1 个答案:

答案 0 :(得分:-1)

根据文档:window.document.domain:获取(无设置)加载文档的服务器的域名。enter link description here