Don
Don

Reputation: 131

Javascript or jquery Event For detecting Back button of the browser

I had some research regarding how to subscribe in the event when back button of the browser is clicked but unfortunately I wasn't able to find the right answer for my problem

I tried doing this:

var $window = $(window);

    $window.on('beforeunload', function()
    {
        commitFieldChanges();
    }); 

i used require JS for this

and the other solution for this is

$(window).bind('beforeunload', function(){ 
    return '';
});

However all of this is not working because my application is a single page app. So the page is not really loading when back button is clicked because we use # to navigate in the application in the URL so what do you think guys? Any suggestion for my problem?

Upvotes: 0

Views: 1454

Answers (1)

choz
choz

Reputation: 17898

This is a way that I currently use for my app, to detect back button on some page which aimed to support modern cross-browsers both desktop and mobile.

Homepage

var isFromView = false;
$(function() {
  // Check if browser supports LocalStorage
  if(typeof(Storage) !== 'undefined') {
    var currentValue = localStorage.getItem('fromSource');
    if (currentValue && currentValue === 'view') {
       // Set isFromDetail to true
       isFromView = true;
    }
    else {
       localStorage.removeItem('fromSource');
    }

    try {
       // Set fromSource in localStorage.
       localStorage.setItem('fromSource', 'home');
    }
    catch (err) {
       // Need this for safari mobile private mode !!
    }
  }
});

Viewpage

$(function() {
  // Check if browser supports LocalStorage
  if(typeof(Storage) !== 'undefined') {
    try {
       // Set fromSource in localStorage.
       localStorage.setItem('fromSource', 'view');
    }
    catch (err) {
       // Need this for safari mobile private mode !!
    }
  }
});

++: I've gone through with history API to perform action on back button. But with no success in supporting some mobile devices browsers.

Upvotes: 1

Related Questions