4

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?

3 Answers 3

4

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 )

Sign up to request clarification or add additional context in comments.

2 Comments

Notice that pushState is not supported in IE <10 or older Android browsers (< 4.2)
@BasSlagter You're right, but we see window.onpopstate in the question that means he knows what is it. Thanks btw ;)
1

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?'; }; 

2 Comments

So, how I can hide myDiv when user tries to go back? Will it works on smartphones?
You can hide it from within the onbeforeunload function but I do not really see any use for it. And yes...it will work on smarphones.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.