JS Iframe跨域访问父document对象

假设有A: 127.0.0.1:8080

          B:  192.168.0.1:7001 

         两个服务器,A的IFrame嵌入B的页面,

由于两个页面不在同一个域和端口下,会报错:Protocols, domains, and ports must match.

怎么实现A对B页面的dom元素的操作呢?

1.实现B页面的扩展

在A服务器下建立一个代理页面,用于B页面dom对象的获取,简称 AProxy.html

这样会形成A和B不同域

A和Aproxy同域

A的Iframe 嵌入B

B的iframe嵌入Aproxy

 

只需要通过Aproxy对其父级B进行dom读取,虽然不属于同一域可以进行doucment.domain的设置

然后通过Aproxy对其A(parent.parent )进行dom设置,以便可以回调 

 

代码如下:

 

 

A页面

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
    <head>
        <title>调用demo</title>
        <meta name="google" value="notranslate" />         
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script>
			document.domain = "192.168.0.1:7001";
			var swfObj = null;
			function setSwfObj(obj){ //这里是代理页面对B页面的dom回调
				if(null == swfObj){
					swfObj = obj;
				}
				return swfObj;
				
			}
			

			function TESTDrawPoints1(){
				var obj =  swfObj.GetExtent();
				alert(obj.xmin+","+obj.ymin);
				//getSwfObject().DrawPoints("点图层","001","116.46,40","circle",20,"ff0000",false,"测试点",true,true,true,"","pointmouseClick","");
			}
		</script>
    </head>
	
<body>
		<input type="button" value="画单个点" onclick="TESTDrawPoints1()"/>
	 
	   <div style="overflow:auto;">
	 		 <iframe id="gframe" name="gframe" src="http://127.0.0.1:7001/B.jsp" width="99%" height="500" > 
		</div>
		 
	
</body>
</html>

 

 AProxy.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
    <head>
        <title>GIS调用demo</title>
        <meta name="google" value="notranslate" />         
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script>
			window.onload = function(){
				document.domain = "192.168.0.1:7001";
				var ssw = window.parent;
			    var swfObj = window.parent.document.getElementById("index");//获取swfObj对象
			   	parent.parent.setSwfObj(swfObj);//设置dom对象,A页面有回调接受
			}
		</script>
    </head>
<body>
</body>
</html>

 

B 页面:在其body之前加入

 

<iframe id="myfarme" src="###" style="display: none;"></iframe> //一定display 为none  这样不会占有空间
        <script>
		    window.onload = function(){
		   	     document.domain = "192.168.0.1:7001";//这个必须设置,设置统一域名
		   	     document.getElementById('myfarme').src="http://127.0.0.1:8080/Aproxy.html";
		    }
		</script>  

 

 

 

你可能感兴趣的:(document)