Kir*_*ril 7 javascript iframe browser-history hashchange
我有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>
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
我使用更改哈希按钮向历史记录添加几个哈希值.当我按下里面的回按钮时iframe- 更改了父页面的哈希值.似乎这是规范的行为.
所以问题是:是否有可能阻止从iframe传回到它的父页面?所以我希望iframe不要改变父级的历史/哈希.
注意:相同的行为是go函数(实际上,go(-1)是相同的back()).
我认为不使用框架就不可能做到这一点,但我有一个解决方案可以(部分)解决这个问题。
首先,我想到更改对象history并重新定义它,但这是不可能的,因为它是窗口内的属性,不可写。但我们可以重新定义里面的函数history。
这就是导致我重新定义函数的原因,我们必须找到以前的 url并更改文档(子文档)的位置,back()而不是让对象完成他的工作。history
在你中Child.html,重新定义函数,back()如下所示:
history.back = function ()
{
document.location = document.referrer;
}
Run Code Online (Sandbox Code Playgroud)
我们在这个函数中遇到的问题是,一旦父文档被加载,并且 iframe(子文档)也被加载,子文档document.referrer的 url 返回父文档的 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;
}
Run Code Online (Sandbox Code Playgroud)
最后,这是我找到的解决方案,不幸的是它有一个问题,就是你无法重新定义forward()允许你转到下一个url的函数,无法找到下一个url,并document.referrer返回页面的url你来自哪里,它可能是上一页或下一页。但您仍然可以在 iframe 内导航,而无需更改父位置。