Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript or jQuery browser back button click detector

Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?

We need to cater all browser that doesn't support HTML5

like image 607
Nil Pun Avatar asked Jul 11 '13 13:07

Nil Pun


People also ask

How can I tell if my back button is pressed in my phone?

One option is to use jquery mobile. According to this source, to detect the 'back' key, KEYCODE_BACK = 4 on Android.


2 Answers

The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {    if (window.history && window.history.pushState) {      window.history.pushState('forward', null, './#forward');      $(window).on('popstate', function() {       alert('Back button was pressed.');     });    } }); 

For browser backward compatibility I recommend: history.js

like image 110
Benny Neugebauer Avatar answered Oct 12 '22 23:10

Benny Neugebauer


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 } 
like image 39
Hasan Badshah Avatar answered Oct 13 '22 00:10

Hasan Badshah