學習資料:
https://www.cnblogs.com/Wayou/p/things_you_dont_know_about_frontend.html#comment_form_container
https://blog.csdn.net/dugujiancheng/article/details/51669164
https://www.cnblogs.com/lvhw/p/7107436.html
方法一:
if(window.location != window.parent.location) { window.parent.location = window.location; }
方法二:
為了防止網站被釣魚,可以使用window.top來防止你的網頁被iframe
if(window != window.top) { window.top.location.href = correctURL; }
方法三:
限定你的網頁不能嵌套在任意網頁內。如果你想引用同於的框架的話,可以判斷域名。
if(top.location.host != window.location.host) {
top.location.href = window.location.href; }
當然,如果你網頁不同域名的話,上述就會報錯。
所以,這里可以使用try...catch...進行錯誤不活。如果發生錯誤,則表明不同域,表示你的頁面被盜用了。可能有些瀏覽器這樣寫不會報錯,所以需要降級處理。
這時候再進行跳轉即可。
try{ top.location.hostname;//檢測是否出錯 //如果沒有出錯,則降級處理 if(top.location.hostname != qwindow.location.hostname) { top.location.href= window.location.href; } } catch(e){ top.location.ref = window.loction.href; }
擴展學習:window.parent與window.top區別 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/top
window.parent返回當前窗口的直接父對象,window.top返回最頂層的窗口對象。當在處理父窗口的子框架(subframe),而你想獲取頂層框架時,window.top屬性相當有用。