javascript location.hash 和回溯历史

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11471008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:20:34  来源:igfitidea点击:

location.hash and back history

javascriptbrowser-cachehashcode

提问by George Filippakos

Is there a function that can be called to prevent the browser from recording a back history entry when changing the hash value?

是否有可以调用的函数来防止浏览器在更改哈希值时记录历史记录条目?

I am writing a simple javascript gallery that changes the browser url without reloading the page as the user moves through each image.

我正在编写一个简单的 javascript 库,它可以在用户浏览每个图像时更改浏览器 url 而不重新加载页面。

This is done by setting the location.hash to the unique ID of the image.

这是通过将 location.hash 设置为图像的唯一 ID 来完成的。

window.location.hash = imageID;

The problem is when the user hits the browser back button, they must move backwards through every image like it was a page load.

问题是当用户点击浏览器后退按钮时,他们必须像加载页面一样向后移动每个图像。

If they rotated through 20 images using the gallery, they must click back 21 times to get back to the previous page.

如果他们使用图库旋转了 20 张图像,则必须单击返回 21 次才能返回上一页。

How can I prevent a back history from being recorded with javascript?

如何防止使用 javascript 记录历史记录?

回答by jalbee

window.location.replacewill let you set the url without adding it to the browser history.

window.location.replace将让您设置 url 而无需将其添加到浏览器历史记录中。

var baseUrl = window.location.href.split('#')[0];
window.location.replace( baseUrl + '#' + imageID );

documentation

文件

回答by Charles

You can use replaceState().

您可以使用replaceState()

Before you change the hash you save the history, then you change your hash, finally you replace the history with the one you saved.

在更改哈希值之前,先保存历史记录,然后更改哈希值,最后用保存的历史记录替换历史记录。

Alternatively you can use popState Event.

或者,您可以使用popState Event