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

贊助商

分類目錄

贊助商

最新文章

搜索

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

作者:admin    時(shí)間:2018-1-16 14:16:42    瀏覽:

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

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

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

要達(dá)到此效果,就要重新編寫(xiě)上面的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ú)法將你的網(wǎng)頁(yè)嵌入框架。

上述代碼在IE、Firefox、Chrome瀏覽器測(cè)試通過(guò)!

完整范例

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)頁(yè)范例</title>
</head>
<body>
iframe引用網(wǎng)頁(yè)范例<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)頁(yè)被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引用的頁(yè)面</b>
</body>
</html>

execcode getcode

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

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

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

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