幾種location.href的區別 js實現網頁防止被iframe架構嵌套功能

來源:互聯網
上載者:User

首先我們瞭解一下:window.location.href、location.href、self.location.href、parent.location.href、top.location.href他們的區別與聯絡,簡單的說:
"window.location.href"、"location.href"、"self.location.href"是本頁面跳轉
"parent.location.href"是上一層頁面跳轉
"top.location.href"是最外層的頁面跳轉

舉個例子說明(如):
如果A,B,C,D都是普通頁面,D是C的iframe,C是B的iframe,B是A的iframe,
如果D中js這樣寫:
"window.location.href"、"location.href":D頁面跳轉
"parent.location.href":C頁面跳轉
"top.location.href":A頁面跳轉

如果D頁面中有form的話:
<form>:  form提交後D頁面跳轉
<form target="_blank">:  form提交後彈出新頁面
<form target="_parent">:  form提交後C頁面跳轉
<form target="_top"> :  form提交後A頁面跳轉

關於頁面重新整理,D 頁面中這樣寫:
"parent.location.reload();": C頁面重新整理  (當然,也可以使用子視窗的 opener 對象來獲得父視窗的對象:window.opener.document.location.reload(); )
"top.location.reload();": A頁面重新整理

現在回頭看看,js實現網頁防止被iframe架構功能就很簡單了。假設frame.html檔案中架構了content.html檔案,那麼思路是這樣的:在content.html中加入js檢測自己本身top.location.href地址,是否為top.location.href地址。如果是則沒被嵌套,如果否的話即被嵌套了,這是我們可以提示一下。預覽效果 

下載源檔案

網頁防止被架構方法代碼:
<script language="javascript">
if(top.location!==self.location){
WarningTxt1 = "content頁面被iframe了!";
WarningTxt2 = "我們跳出iframe,直接存取content頁面吧!";
alert(WarningTxt1);
alert(WarningTxt2);
top.location.href=self.location.href;
}
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.