How to Detect Browser Back Button event – Cross Browser

How to Detect Browser Back Button event – Cross Browser

How do you definitively detect whether or not the user has pressed the back button in the browser?
How do you enforce the use of an in-page back button inside a single page web application using a #URL system?
Why on earth don’t browser back buttons fire their own events!?


Solution 1:

(Note: As per Sharky’s feedback, I’ve included code to detect backspaces)

So, I’ve seen these questions frequently on SO, and have recently run into the issue of controlling back button functionality myself. After a few days of searching for the best solution for my application (Single-Page with Hash Navigation), I’ve come up with a simple, cross-browser, library-less system for detecting the back button.

Most people recommend using:

window.onhashchange = function() {
 //blah blah blah

However, this function will also be called when a user uses on in-page element that changes the location hash. Not the best user experience when your user clicks and the page goes backwards or forwards.

To give you a general outline of my system, I’m filling up an array with previous hashes as my user moves through the interface. It looks something like this:

function updateHistory(curr) {
    window.location.hash = curr;

Pretty straight forward. I do this to ensure cross-browser support, as well as support for older browsers. Simply pass the new hash to the function, and it’ll store it for you and then change the hash (which is then put into the browser’s history).

I also utilise an in-page back button that moves the user between pages using the lasthash array. It looks like this:

function goBack() {
    window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
    //blah blah blah

So this will move the user back to the last hash, and remove that last hash from the array (I have no forward button right now).

Related:  Detecting Unsaved Changes

So. How do I detect whether or not a user has used my in-page back button, or the browser button?

At first I looked at window.onbeforeunload, but to no avail – that is only called if the user is going to change pages. This does not happen in a single-page-application using hash navigation.

So, after some more digging, I saw recommendations for trying to set a flag variable. The issue with this in my case, is that I would try to set it, but as everything is asynchronous, it wouldn’t always be set in time for the if statement in the hash change. .onMouseDown wasn’t always called in click, and adding it to an onclick wouldn’t ever trigger it fast enough.

This is when I started to look at the difference between document, and window. My final solution was to set the flag using document.onmouseover, and disable it using document.onmouseleave.

What happens is that while the user’s mouse is inside the document area (read: the rendered page, but excluding the browser frame), my boolean is set to true. As soon as the mouse leaves the document area, the boolean flips to false.

This way, I can change my window.onhashchange to:

window.onhashchange = function() {
    if (window.innerDocClick) {
        window.innerDocClick = false;
    } else {
        if (window.location.hash != '#undefined') {
        } else {
            history.pushState("", document.title, window.location.pathname);

You’ll note the check for #undefined. This is because if there is no history available in my array, it returns undefined. I use this to ask the user if they want to leave using a window.onbeforeunload event.

So, in short, and for people that aren’t necessarily using an in-page back button or an array to store the history:

document.onmouseover = function() {
    //User's mouse is inside the page.
    window.innerDocClick = true;

document.onmouseleave = function() {
    //User's mouse has left the page.
    window.innerDocClick = false;

window.onhashchange = function() {
    if (window.innerDocClick) {
        //Your own in-page mechanism triggered the hash change
    } else {
        //Browser back button was clicked

And there you have it. a simple, three-part way to detect back button usage vs in-page elements with regards to hash navigation.

Related:  npm install the exact package version specified in package.json


To ensure that the user doesn’t use backspace to trigger the back event, you can also include the following (Thanks to @thetoolman on this Question):

     * this swallows backspace keys on any non-input element.
     * stops backspace -> back
    var rx = /INPUT|SELECT|TEXTAREA/i;

    $(document).bind("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test( || || ){

Solution 2:

You can try popstate event handler, e.g:

window.addEventListener('popstate', function(event) {
    // The popstate event is fired each time when the current history entry changes.

    var r = confirm("You pressed a Back button! Are you sure?!");

    if (r == true) {
        // Call Back button programmatically as per user confirmation.
        // Uncomment below line to redirect to the previous page instead.
        // window.location = document.referrer // Note: IE11 is not supporting this.
    } else {
        // Stay on the current page.
        history.pushState(null, null, window.location.pathname);

    history.pushState(null, null, window.location.pathname);

}, false);

Note: For the best results, you should load this code only on specific pages where you want to implement the logic to avoid any other unexpected issues.

The popstate event is fired each time when the current history entry changes (user navigates to a new state). That happens when user clicks on browser’s Back/Forward buttons or when history.back(), history.forward(), history.go() methods are programatically called.

The event.state is property of the event is equal to the history state object.

For jQuery syntax, wrap it around (to add even listener after document is ready):

(function($) {
  // Above code here.

See also: window.onpopstate on page load

See also the examples on Single-Page Apps and HTML5 pushState page:

// jQuery
$(window).on('popstate', function (e) {
    var state = e.originalEvent.state;
    if (state !== null) {
        //load content with ajax

// Vanilla javascript
window.addEventListener('popstate', function (e) {
    var state = e.state;
    if (state !== null) {
        //load content with ajax

This should be compatible with Chrome 5+, Firefox 4+, IE 10+, Safari 6+, Opera 11.5+ and similar.

Related:  Implementing MongoDB 2.4's full text search in a Meteor app

Solution 3:

I had been struggling with this requirement for quite a while and took some of the solutions above to implement it. However, I stumbled upon an observation and it seems to work across Chrome, Firefox and Safari browsers + Android and iPhone

On page load:

window.history.pushState({page: 1}, "", "");

window.onpopstate = function(event) {

  // "event" object seems to contain value only when the back button is clicked
  // and if the pop state event fires due to clicks on a button
  // or a link it comes up as "undefined" 

    // Code to handle back button or prevent from navigation
    // Continue user action through link or button

Let me know if this helps. If am missing something, I will be happy to understand.

Solution 4:

In javascript, navigation type 2 means browser’s back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2)
    //Do your code here

Solution 5:

This will definitely work (For detecting back button click)

$(window).on('popstate', function(event) {

Solution 6:


For mobile control:

$(document).ready(function() {
  $('body').on('click touch', '#share', function(e) {

// geri butonunu yakalama
window.onhashchange = function(e) {
  var oldURL = e.oldURL.split('#')[1];
  var newURL = e.newURL.split('#')[1];

  if (oldURL == 'share') {
    return false;
  //console.log('old:'+oldURL+' new:'+newURL);
.share{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.8); color:white; padding:20px;
<!DOCTYPE html>

    <title>Back Button Example</title>
    <script src=""></script>


<body style="text-align:center; padding:0;">
    <a href="#share" id="share">Share</a>
    <div class="share" style="">
        <h1>Test Page</h1>
        <p> Back button press please for control.</p>