Search code examples
javascripthtmlgoogle-chromeoperahtml5-history

Chrome/Opera `window.onpopstate` bug


I'm trying to handle window.onpopstate event in my single page app and in Google Chrome and Opera it doesn't work.

This is my simple html page

<html>
    <head>
        <meta charset="utf-8" />
        <script>
        window.onpopstate = function(e) {
            alert('onpopstate');
        }
        setTimeout(function () {
            history.pushState(1, 'Hello John', '/hello/john');
        }, 2000);
        setTimeout(function () {
            history.pushState(2, 'Hello Emily', '/hello/emily');
        }, 3000);
        </script>
    </head>
    <body></body>
</html>

When I hit browser's back button I expect to see alert with onpopstate text to be shown. In Safari, Firefox, Vivaldi it works as expected. In Chrome and Opera it never called, it is just going to previous page by reloading it which is bad scenario for my SPA.

What is more weird is that I found some trick to make it work:

  1. go to dev tools, console tab
  2. simply execute console.log(history) or even console.log(window) and it magically starts working! But if I do the same in script on the page with or without timeout this trick doesn't work at all. So the only way to make onpopstate work which I found is to manually go to console and execute console.log(history).

Maybe I'm missing something? Any help would be appreciated.

My environment:

  • macOS 11.0.1 (20B29)
  • Chrome 87.0.4280.67 (Official Build) (x86_64)
  • Opera 72.0.3815.378

Posted Chromium bug

SOLUTION:

Ok, this is not a bug, it is a feature! It is kinda interact first feature of Chromium. If user interact first somehow with a page then everything gonna work, otherwise back button will go back with reloading.

So e.g. just add some button into body and click on it first, then try to click back in browser.

<body>
    <button onclick="alert('hello');">alert</button>
</body>

Solution

  • To be able to run some javascript like moving on history or play sounds or pop up windows the user first hast to interact (click) on the web site.

    you can find more info here:

    WebUpdates 2017