javascript - 怎么破解top.location.href =window.location.href,通过iframe嵌入别人网页?

查看:236
本文介绍了javascript - 怎么破解top.location.href =window.location.href,通过iframe嵌入别人网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如题,可能讲的不太明白。
手头有个需求,产品经理说:小胡啊,我们产品要新增一个功能,就是能够将别写得好的H5页面展现出来,或者向用户提供网页展示,比如展示某某新闻网站
我想啊,既然要做这么流氓的事,以前都用iframe来嵌入第三方页面,还是用这个吧,况且别的方法也没找到。
然后问题就来了,比如某新闻网站嵌过来就反客为主了,直接把我的html页面干掉了!经过不懈的努力,发现原来是该网页有反运营商劫持代码;代码如下:

<!-- 反运营商劫持 S -->
<style type="text/css">
    html {
        display:none;
    }
    </style>
<script>
    if( self == top ) {
        document.documentElement.style.display = 'block' ;
    } else {
        top.location = self.location ;
    }
    </script>
<!-- 反运营商劫持 E -->

哪位大神能帮忙破解吗?

采用过以下方法:

//在主窗口的</head>标签前面添加 
<script type="text/javascript"> 
var location=document.location 
</script>
//或者: 
<script type="text/javascript">
var location="" 
</script>

然并卵。。。

解决方案

一楼答主所言极是;
目前的解决方案是通过ifram的沙盒属性sandbox来禁止跳转;
所有主流浏览器都支持 sandbox 属性。但IE 9 以及更早的版本不支持 sandbox 属性,Opera 12 以及更早的版本也不支持该属性
如果您要兼容IE8及以下,请忽略答案!!!
iframe的sandbox属性及值:

不设置allow-top-navigation就不会被强制跳转了!!!
当然,你会发现不跳转但是页面内容不显示,以xw.qq.com为例,你会发现是因为iframe中的html被设置了"display:none";

  //以下代码在已webview形式嵌套到android中的html页面有效
  $(window.frames["iframe的id"].document).find("html").css('display', 'block') //基于jQuery

在pc端暂时没找到解药
报错跨域!!

正常界面(android webview中的前端页面):

代码(自行调试,pc绕过!):
var iframe = document.createElement("iframe");

    iframe.id = "iframeId";
    iframe.src = "xw.qq.com";
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.sandbox = "allow-scripts allow-same-origin";
    iframe.frameborder = "0";
    iframe.scrolling = "no";
    iframe.marginwidth = "0";
    iframe.marginheight = "0";
    iframe.border = "0";
       if (! /*@cc_on!@*/ 0) { //浏览器 不是IE的情况下
        iframe.onload = function () {
            console.log("已经加载完成!/no IE");
            $(window.frames["iframeId"].document).find("html").css('display', 'block');
        };
    } else {
        iframe.onreadystatechange = function () {
            if (iframe.readyState == "complete") {
                console.log("已经加载完成!/ IE");
                $(window.frames["iframeId"].document).find("html").css('display', 'block');
            }
        };
    }
    $this.appDom.html(iframe);
    

这篇关于javascript - 怎么破解top.location.href =window.location.href,通过iframe嵌入别人网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆