0

I'm using pushState to have adaptative URLs on a single-page web app. I'm also using onpopstate to have native-like behaviour with mobile devices' back button. I have managed not to lock the user out of their history, which is everyone's main concern on the threads I read mentioning how to do it.

It seems however that the trick I'm using only works when the window is clicked. Even scrolling doesn't work. It's a problem because users might not necessarily click and still hit the back button to close a menu. I've only tried it in Chrome with the following code :

window.onload = function(){
    history.pushState({}, '', '')
}

window.onpopstate = function(){
    history.pushState({}, '', '')
}

You have to open a new tab, browse to the file and hit the back button. If you don't click the content of the page before, it should walk back in history instead of being locked by the script. I've tried to use .focus and .click with no success.

Any ideas?

EDIT

This is what this person is talking about, and they definitely phrased it better than I did

The popstate solution works for my PWA, however I just want to point out that, from my experience, Chrome WILL close the PWA if it doesn't detect ANY user interaction, before the click on Android's back button (the interaction can be a link click, zoom-in, scroll ...). I was testing this code snippet on a minimal sample app, and couldn't understand why it wasn't working. I assume it is a safety measure against spam pop-ups, but hadn't read anything about it in the guides fetched by Google.

Seems like PWA aren't quite there yet.

Tim
  • 71
  • 6
  • I'm confused, doesn't the browser create a history entry anyway on `window.onload`? Where do you push state in your app e.g. your menu? – tobiv Aug 26 '22 at 12:41
  • It does, but the onpopstate function will not create the new state in time before the browser switches the the previous page, so you need to create an other one on load. – Tim Aug 26 '22 at 13:07
  • Aha I get now. I can't reproduce this right now, but could a [simulated interaction](https://stackoverflow.com/a/2706236/1848468) work? – tobiv Aug 26 '22 at 15:33
  • Thank you for your help. I'm not sure I've understood that post quite fully but adding this to the onload function doesn't work: setTimeout(function(){ document.querySelectorAll('h1')[0].dispatchEvent(new Event( "click", { bubbles: true } )) console.log('click!') },1000) – Tim Aug 27 '22 at 14:03

0 Answers0