[英]Prevent history propagation to the parent window
我有2個簡單的html頁面:父母和孩子。 父將子存儲在iframe
。
Parent.html:
<html>
<head></head>
<body>
<input type="text" id="text" />
<input type="button" value="change hash" onclick="javascript:changeHash()" />
<iframe src="Child.html"></iframe>
<script type="text/javascript">
function changeHash () {
window.location.hash = document.getElementById('text').value;
}
</script>
</body>
</html>
和Child.html:
<html>
<head></head>
<body>
<input type="button" value="go back" onclick="javascript:goBack()" />
<script type="text/javascript">
function goBack () {
this.history.back();
}
</script>
</body>
</html>
我使用更改哈希按鈕向歷史記錄添加幾個哈希值。 當我在iframe
按回去按鈕時 - 父頁面的哈希值會發生變化。 似乎這是規范的行為。
所以問題是:是否有可能阻止從iframe傳回到它的父頁面? 所以我希望iframe不要改變父級的歷史/哈希。
注意: go
函數的行為相同(實際上, go(-1)
與back()
相同)。
我認為使用框架不可能做到這一點,但我有一個可以(部分)解決這個問題的解決方案。
首先,我想到了改變對象history
並重新定義它,但這是不可能的,因為它是窗口內不可寫的屬性。 但我們可以重新定義history
的功能。
這導致我重新定義函數back()
而不是讓history
對象完成他的工作,我們必須找到前一個url並更改文檔(child)的位置。
在你的Child.html
,重新定義函數back()
如下所示:
history.back = function ()
{
document.location = document.referrer;
}
我們在這個函數中遇到的問題是,一旦加載了父文檔,並且也加載了iframe(子),子document.referrer
返回父document.referrer
的url
所以,在更改document.location
之前,讓我們測試一下document.referrer
是否與父的url不同(沒有錨點)
history.back = function ()
{
var url = window.parent.document.location.href.split("#")[0];
if(document.referrer!=url)
document.location = document.referrer;
}
最后,這是我找到的解決方案,不幸的是它有一個問題,就是你無法重新定義函數forward()
,它允許你轉到下一個url,找不到下一個url和document.referrer
返回您來自的頁面的網址,可以是上一頁或下一頁。 但仍然可以在更改父位置的情況下在iframe內導航。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.