即使更改了哈希值,如何在单击网页中的“浏览器后退”按钮时也如何返回上一页?

时间:2018-10-16 22:49:00

标签: javascript jquery html5

我有一个网页,其中我的锚标记使用#id引用同一页面中的元素之一。但这会更改我的URL,因为它会将#id添加到后缀中。因此,现在,当我想通过单击浏览器的“后退”按钮返回到我所在的页面时,它不会返回到上一页,而是返回到我通过单击锚点标记所做的哈希选择。请为此提供解决方案。

2 个答案:

答案 0 :(得分:1)

使用散列路由时,它会在浏览器历史记录中创建新记录,就像您导航到新页面一样。因此,如果您在网站上从页面导航到该页面上的哈希路由,然后导航到新页面,则必须单击两次后退按钮才能返回到原始位置。

因此,如果您浏览https://example.com -> https://example.com#myHash -> https:/example.com/another-page,则后退按钮的第一次单击将导航至https://example.com#myHash,而后退按钮的第二次单击将导航至https://example.com

希望有帮助

答案 1 :(得分:0)

您可以使用History API中的history.replaceState()函数来实现这种行为。当用户单击锚点时,您将只替换当前历史记录项,而不添加新项。

编辑:window.location.replace()

另一种方法是使用window.location.replace(),它不会在浏览器的“历史记录”中添加新条目:

  

Location.replace()方法用提供的URL中的资源替换当前资源。与Assign()方法的区别在于,使用replace()之后,当前页面将不会保存在会话历史记录中,这意味着用户将无法使用后退按钮导航到该页面。

因此,要获得所需的结果,可以在body元素上添加一个onclick处理程序,并在其中添加逻辑,如果当前位置不是主页(或任何其他页面),该逻辑将替换当前位置。该处理程序的外观类似于以下代码:

function handler (event) {
    if (!isAnchor(event.target) return;                     // return if clicked element is not an anchor (isAnchor function should be also implemented by you. For example, you can add some class on every anchor and check if clicked element is <a> tag with this class)
    if (window.location.href !== window.location.origin) {  // check if you are currently on the homepage
        event.preventDefault();                             // if not on homepage then prevent default <a> tag redirect 
        window.location.replace(event.target.href);         // and replace current history item URL with the new URL
    }
}