I'm trying to implement some navigation resistance when a user tries to navigate away from a certain view in our single page app. Basically I want to call something along the lines of a confirm(msg)
before the hash changes. I want it to behave similarly to onbeforeunload
.
I found this question and tried out the suggested answer: How can i execute code before hashchange
The problem with the one (unaccepted) answer to the above question is that it's using $(window).on('hashchange',...)
, then when the hash changes it does a confirm when you're already on the new view and tries to navigate you back to the previous page. This is not good UX, and on top of that if you have forms or a save in progress on that page, you lose all the state info from before you navigated away.
I tried changing his answer to use $(window).before('hashchange',...)
but all that did was blow up in my face with a bizarre, seemingly unrelated error (see error text below). I haven't seen anything anywhere on how to intercept a hashchange
event before the hash actually changes. Anybody have any suggestions?
Error message text:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
Edit
Ok so apparently I'm attempting to misuse .before
so disregard that part. I still need to intercept the hashchange
event before it acts on the page