Reputation: 2107
Sorry if duplicate, but I don't understand how I can use the basic approach in my case. I need to hide some div, when user presses back button in browser. That is all what I need. The page must not to be reloaded. I tried this way:
window.onpopstate = function (event) {
event.preventDefault();
alert("Back button pressed");
myDiv.style.display = 'none';
}
But this doesn't work at all. Even alert doesn't fire. And the browser goes back as always.
How to make it work? First of all this must works in mobile browsers.
Will the using of window.location.hash
trigger page reloading or not?
Upvotes: 4
Views: 16293
Reputation: 11
i use the before unload thing:
window.addEventListener('beforeunload', waitForUpdate);
and the purpose is to save the user-made changes before they leave + handle any ocasional swipes.
function waitForUpdate(e) {
updateBooks(e);
e.preventDefault();
e.returnValue = 'Wait a sec.';
return 'You have unsaved changes. Are you sure you want to leave?';
}
and so in a desktop browser it works - shows the (default tho) prompt and gives the options: leave/stay. on mobile tho the both options result pwa exit. any way tork around that? i'd like to make it so user can prevent the exiting.
tho the main purpose (the books update thing) does work - the http request gets fired before unload while the default leave/stay thing hangs.
Upvotes: 0
Reputation: 955
Short answer: You can't change it.
Long answer:
You should first set a State
then get it with event handler.
So, simply, when user clicks on a specific section of your document, for example a <a>
, you set a State
then when he clicks on back button ( of browser ) you've got a fired event.
someElement.addEventListener( 'click', function( e ) {
history.pushState({ state: 'someElement was clicked' }, 'title', 'some-element.html' );
})
Now, as back button pressed, you've got an alert ( as presented in your question ).
For furthur information check here: Manipulating the browser history( mdn )
Upvotes: 4
Reputation: 9929
No, changing the location hash will not do a page reload (this is where all Single Page Applications are based upon.
Preventing the behaviour after the back button is clicked (which will trigger a page reload) is not really an option. Best you can do is warn the user:
window.onbeforeunload = function() {
return 'Sure you want to leave?';
};
Upvotes: 1