防止历史记录传播到父窗口

Prevent history propagation to the parent window

本文关键字:窗口 传播 记录 历史      更新时间:2023-09-26

我有两个简单的html页面:父和子。Parent将child存储在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>

我使用change hash按钮向历史记录添加几个哈希值。当我按返回iframe内的按钮时,父页面的哈希值被更改。这似乎是规范的行为。

所以问题是:是否有可能防止传播从iframe回到它的父页?所以我希望iframe不要改变父节点的历史/散列。

注:go函数相同(实际上,go(-1)back()相同)。

我认为不使用框架是不可能做到这一点的,但是我有一个解决方案可以(部分地)解决这个问题。

首先,我想改变对象history并重新定义它,但这是不可能的,因为它是窗口内的属性,不可写。但是我们可以重新定义history内部的函数。

这就是导致我重新定义函数back()的原因,而不是让history对象做他的工作,我们必须找到以前的url并改变文档(子)的位置。

Child.html中,像这样重新定义函数back():

history.back = function ()
{
    document.location = document.referrer;
}

我们在这个函数中遇到的问题是,一旦父文档被加载,iframe(子)也被加载,子文档的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返回你来自的页面的url,它可能是前一页或下一页。但是你仍然可以在iframe内部导航而不改变父位置。