简体   繁体   中英

JavaScript location.href doesn't add record to browser history

There are three pages, A, B and C. A has a tag whose href redirects to B. B has JavaScript Code and redirects to C. When in C, I click browser back button, browser redirects to A. Why not B ? Thank you in advance.

Test Links Page A: http://o17o2o.com:8000/article-href.html

Page A

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Test</title>
</head>
<body>
    <a href="/href-redirect.html">click me</a>
</body>
</html>

Page B

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>waiting</title>
</head>
<body>
    Page B
    <script type="text/javascript">
        window.location.href = '/original.html';
    </script>
</body>
</html>

location.href redirect will only add to browser history if it is from user initiated action. Here you are calling it on onload event so it wont be added to history

user History.pushState to insert in browser history

I have an observation here. If we add a setTimeout before calling location.href programmatically, say a 2 sec delay, the current page gets added in the history. Looks like this behavior is somewhat asynchronous and it happens in all browser. I wonder why this bug is not solved for so long.

手动测试:如果用户没有先与文档交互(如keydown、click,但不是wheel),以编程方式调用location.href=xx,当前页面不会添加到历史记录中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM