技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

【JS實現(xiàn)】同域可以但禁止異域網(wǎng)站用iframe嵌入網(wǎng)頁

作者:admin    時間:2018-1-16 14:16:42    瀏覽:

網(wǎng)頁禁止被iframe嵌入的方法,我想很多人都知道怎樣用JS實現(xiàn)了,如果你還不知道,請看如下代碼:

<script type="text/javascript">
if (window!=top) // 判斷當(dāng)前的window對象是否是top對象
  top.location.href = window.location.href; // 如果不是,將top對象的網(wǎng)址自動導(dǎo)向被嵌入網(wǎng)頁的網(wǎng)址
</script>

代碼很簡單,但是上述代碼是無論任何網(wǎng)站都不能用iframe嵌入該網(wǎng)頁,然而我們更希望自己的網(wǎng)站可以嵌入該網(wǎng)頁,僅禁止其他網(wǎng)站嵌入即可。

要達(dá)到此效果,就要重新編寫上面的JS代碼了,修改后的代碼如下:

<script type="text/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>

使用此代碼后,除了本地域名以外,其他域名一律無法將你的網(wǎng)頁嵌入框架。

上述代碼在IE、Firefox、Chrome瀏覽器測試通過!

完整范例

example.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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>iframe引用網(wǎng)頁范例</title>
</head>
<body>
iframe引用網(wǎng)頁范例<br>
<iframe src="http://www.howtostagehomes.com/tutorial/js/2018/011623/js-no-iframe.html" style="width:600px;height:350px;border:1px;"></iframe>
</body>
</html>

js-no-iframe.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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用JS防止網(wǎng)頁被Frame框架調(diào)用</title>
<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>
</head>
<body>
<b>這是被iframe引用的頁面</b>
</body>
</html>

execcode getcode

網(wǎng)上有些文章說可以破解,讓此JS代碼失效,此方法不再生效,以致仍然可以用iframe嵌入網(wǎng)頁,果真如此?請看《【輕易破解】使用JS防止網(wǎng)頁被Frame框架調(diào)用?》。

使用X-Frame-Options防止網(wǎng)頁被Frame

上面提到用JS防止網(wǎng)頁被iframe嵌入,其實最好的方法是使用 X-Frame-Options 防止網(wǎng)頁被Frame,使用 X-Frame-Options 可以輕松設(shè)置同域可以但禁止異域網(wǎng)站用iframe嵌入網(wǎng)頁,可參考我此前寫的文章《360安全提示“X-Frame-Options頭未設(shè)置”的解決方法(IIS)》、《web.config 設(shè)置 X-Frame-Options 的方法【親測有效】》。

標(biāo)簽: iframe  frame  
x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */