Sunday 13 December 2015

Handle back button using Javascript

Some times developers need to handle/disable the back button functionality. In situations like after payment screen or after logout, users going back using back button is a weird thing for any developer.

To handle this situation, add the following JavaScript code in your navigated page.

<script type = "text/javascript" >
        history.pushState(null, null, 'page_name');
        window.addEventListener('popstate', function(event) {
            history.pushState(null, null, 'page_name');
        });
</script>

Replace the "page_name" with your navigated page name.

Ex: If you are navigating from first.html to second.html. Add the above snippet in second.html page and replace "page_name" with "second.html".

That's it. 

Enjoy coding.