Chrome popstate not firing on Back Button if no us

2020-06-10 06:26发布

I'm trying to use "pushState" and the "popstate" event to trap Back button navigation, however, while the popstate event triggers correctly in Firefox, it doesn't trigger in Chrome (Version 76.0.3809.87 (Official Build) (64-bit)) if there is no user interaction.

From testing, it looks like the popstate event only gets triggered if the user interacts with the page (ie. clicks somewhere on the document). So if you load the page without interacting and hit Back, the popstate function is not called.

I've added a Fiddle to showcase this: https://jsfiddle.net/0xwvLndu/

To test the Fiddle in Chrome, just click the link and hit the Back button. You'll see no alert. Then click the link again but this time click anywhere on the Fiddle document and then hit the Back button, the alert is then triggered.

I found a discussion on the Chromium forum that may relate to this quirk, and perhaps this has been implemented to prevent abuse of history entries - https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/OCS7g72HtyI and https://github.com/WICG/interventions/issues/21#issuecomment-425609246

If this is the case, does it mean that popstate cannot be relied on anymore to trap Back button actions, and if so, is there a work around solution?

Below is an example of what I've been testing with:

window.addEventListener('load', function() {
    history.pushState(null, null, document.URL);
});

window.addEventListener('popstate', function(event) {
    alert('test');
});

I expected the alert to be triggered on Back Button regardless of user interaction, but this does not happen in Chrome.

0条回答
登录 后发表回答