gpt4 book ai didi

javascript - 防止历史传播到父窗口

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:49 26 4
gpt4 key购买 nike

我有 2 个简单的 html 页面:父页面和子页面。 Parent 将 child 存储在 iframe 中。
父级.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 内的 go back 按钮时 - 父页面的哈希值已更改。并且这似乎是 spec 的行为.

所以问题是:是否可以防止从 iframe 返回到其父页面的传播?所以我希望 iframe 不要更改父级的历史记录/哈希。

注意: go 函数的行为相同(实际上,go(-1)back( )).

最佳答案

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

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

这就是促使我重新定义函数 back() 的原因,而不是让 history 对象完成他的工作,我们必须 find the previous url并更改文档(子)的位置。

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

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

我们在这个函数中遇到的问题是,一旦加载了父文档,并且也加载了 iframe(子),子的 document.referrer 返回父的 url

因此,在更改 document.location 之前,让我们测试一下 document.referrer 是否与父级的 url(无 anchor )不同

history.back = function ()
{
var url = window.parent.document.location.href.split("#")[0];
if(document.referrer!=url)
document.location = document.referrer;
}

最后,这是我找到的解决方案,不幸的是它有一个问题,就是你不能重新定义允许你转到下一个url的函数forward(),这是不可能的查找下一个 url,document.referrer 返回您来自的页面的 url,它可以是上一页或下一页。但您仍然可以在 iframe 内导航而无需更改父位置。

关于javascript - 防止历史传播到父窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com