`
zhk0377
  • 浏览: 9843 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

中间页js解决iframe跨域内容

阅读更多

场景:

       网站www.a.com (此网站所有页面为纯html的页面),有一功能菜单“论坛”,点击论坛可跳转到论坛网站www.b.com(使用的是开源 的 discuz),在论坛中点击首页也可以跳回  www.a.com主页

需求:

       在www.a.com 添加 注册、登录、显示当前登录用户、注销功能,要求使用www.b.com的注册登录页面。

       注册、登录加 www.b.com的相应连接即可,难就难在  注销、显示当前登录用户上。网站a的首页如何判断论坛是否登录,从而确定该显示“登录|注册” 还是显示“userName|注销”? 最折腾人的就是这个了。

 

 

 

       思路一:ajax请求网站b获取登录信息? 试过,根本不行,经查证,ajax是不支持跨域访问的(浏览器的限制,大家可以尝试一下)。

       思路二:这时,想到了iframe。  在 网站b( discuz)里新建一个页面,回显出 ($discuz),通过iframe加载进来,判断iframe内容,来区分。这个解决方案网上很多,可惜真的都不好使。他们的思路大概如下:iframe.contentWindow.document.body.innerHTML  

     通过 setTimeOut 或  setinterval 去 判断iframe 加载状态/获取iframe内容 

折腾了好一会,最终却提示 没有获取document的权限。从这个错误提示中,我才醒悟,想到了原来是跨域的问题。

     最终解决方案:  利用中间页面。  假设网站 a 下面有两个页面 a.html c.html ,网站b下面有页面b.php  ,页面a 里iframe 的src 为页面b,在页面b中 window.location.href=c.html;把需要传递的内容 通过参数的形式传递给c.html; 在c.html 通过 top.函数名 就可以调到  a.html页面中的函数(此时c.html 位于 a.html的iframe中)

   代码如下: a.html(index.html)

         function changeDiv(username,formhash){
        	    	 	 if("-1"==username){
        	    	 		 $('#logonDiv').html('<a href="http://localhost/bbs/member.php?' +
        	                          'mod=logging&action=login">登录</a>|' +
        	                          '<a href="http://localhost/bbs/member.php?' +
        	                          'mod=register">注册</a>');
        	    	 	 }else{
        	    	 		$('#logonDiv').html(username+'[<a href="http://localhost/bbs/member.php?'+
        	    	 				         'referer=http://localhost:8080/aerotq&mod=logging&action=logout&formhash='+
        	    	 				        formhash+'" target="_top">注销</a>]');
        	    	 	 }
        	}




        <div id="logonDiv" class="logon">
        		<iframe id="iframe"  style="margin-top:30px;"  marginwidth="0" marginheight="0"
                        hspace="0" vspace="0" frameborder="0" scrolling="no"
                        src="http://localhost/bbs/getUser.php"></iframe>
        </div>

    c.html(domainconnect.html)

<script type="text/javascript">  
    var arr=window.location.href.split("?");
    var username=arr[1].split('&')[0].split('=')[1];
    username=decodeURI(username)
    var formhash=arr[1].split('&')[1].split("=")[1];
    top.changeDiv(username,formhash);  
</script>

  b.php(getUser.php)

<?

require 'source/class/class_core.php';//引入系统核心文件
$discuz = &discuz_core::instance();//以下代码为创建及初始化对象
$discuz->cachelist = $cachelist;
$discuz->init();//以上是调用discuz公共执行类等核心代码
if(''==$_G['username']){
    $discuz_user = -1;
}else{
    $discuz_user = $_G['username'];
}

$formhash=formhash();
echo '<script>window.location ="'
     ."http://localhost:8080/aerotq/domainconnect.html?userName=$discuz_user&formhash=$formhash"
     .'";</script>';
?>

 

 

 
 
  • 大小: 21.7 KB
  • 大小: 15.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics