js關閉被開啟的iframe頁面,並在新視窗開啟
阿新 • • 發佈:2022-04-08
示例程式碼:
$(function(){ console.log(window.location.href) if (self.frameElement && self.frameElement.tagName == "IFRAME") { // alert('在iframe中'); window.open(window.location.href) parent.location.reload(true); var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); } });
相關知識補充: 判斷頁面是否被iframe有三種方法
//方式一 if (self.frameElement && self.frameElement.tagName == "IFRAME") { alert('在iframe中'); } //方式二 if (window.frames.length != parent.frames.length) { alert('在iframe中'); } //方式三 if (self != top) { alert('在iframe中'); }
禁止頁面被別人iframe
<script language="javascript"> if(top.location != location) { top.location.href = location.href; } </script> //或 <script language="javascript"> if(self!=top){top.location.href=self.location.href;} </script>
注: 這種做法雖簡單,但如果對方用如下招數很容易就被破解了
<iframe src="你的頁面地址" name="tv" marginwidth="0" marginheight="0" scrolling="No" noResize frameborder="0" id="tv" framespacing="0" width="580" height="550" VSPACE=-145 HSPACE=-385></iframe> <script language="javascript"> varlocation=""; var navigate=""; frames[0].location.href=""; </script>
當然,萬能的js依舊設計了應對招數
<script language="javascript">if(top != self){location.href = "about:blank"; //也可設定為你自己的URL}</script>
但這種方式會禁止所有的頁面的嵌入,那麼本域名內的頁面嵌入也是被禁止 下面做到禁止除域名外的頁面的iframe
<script language="JavaScript"> try{ top.location.hostname; if (top.location.hostname != window.location.hostname) { top.location.href =window.location.href; } } catch(e){ top.location.href = window.location.href; } </script>