1

Could you please let me know how to detect any browser back button click using java script or jquery?

I am using the below :

if(window.history && window.history.pushState){
            window.history.pushState({page:this.href}, null, 'this.href');
            $(window).on('popstate', function() {
              event.preventDefault();
              $('#releaseLicenseApp').modal();
            });
        }

but it is not working in chrome and ie and firefox.

3
  • You can't. You're not allowed to interfere with the use of the back and forward buttons. Malware sites used to do this to prevent people from leaving their page. Commented Aug 29, 2014 at 8:44
  • @Barmar, I have one requirement in my project if I am in user creation page and if I click on back browser button then, I need to show 'Please save your changes before navigating to other page, if you continue then your unsaved data will be lost'. Then how to do this? Commented Aug 29, 2014 at 8:47
  • Why only the back button? Shouldn't they get that message if they try to close the page, too? Use the beforeunload handler. Commented Aug 29, 2014 at 8:50

2 Answers 2

2

As you mentioned in the comments, you only want to notify the user that there are unsaved changes when he tries to leave the page. This can be done using onbeforeunload:

window.onbeforeunload = function(){
  return 'Please save your changes before navigating to other page, if you continue then your unsaved data will be lost.';
};
Sign up to request clarification or add additional context in comments.

4 Comments

What my requirement is, if user clicks on browser back/forward button I want to show "Please save your changes before navigating to other page, if you continue then your unsaved data will be lost." with Yes and No button. If user clicks on Yes then, it will navigate to the backword/forward else it will stay on the same page
The snippet I posted will exactly do that and create a confirm box with two buttons.
No, it is shwoing Leave this page or Stay on this page as button. I want Yes and No as button.
You can't modify the default dialogue for onbeforeunload. You should match your text to the buttons action.
0

Please try this on , it's working on chrome, ie and firfox

<script type="text/javascript">
            window.history.forward();
            function noBack()
            {
                window.history.forward();
            }
    </script>
    <body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload=""> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.