You can have a look at JavaScript function that does this https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onbeforeunload_dom
It’s not great on iOS though.
It’s also implemented in the HashRouting module - https://github.com/s-cork/HashRouting/blob/master/README.md