Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect is that back button OR forward button clicked by javascript?

Just to ensure, I am NOT asking how to catch back/forward button events.

window.addEventListener('popstate', function (e) {
                       alert("Yahoooo!!!!"); 
                   });

That function above is triggered either it is browser's back button or browser's forward button but I cannot detect which one was clicked? Was it back button or forward button?

Is there any specific event for them that I can detect it was "back" or "forward" button specifically?

EDIT: While I appreciate the "duplicate question" suggestion, the similar question posted here on stackoverflow but the accepted answer is from January 2012!! A lot of things changed since then. Maybe there is already easier way for this!

Thanks

like image 633
curiousBoy Avatar asked Jan 19 '26 03:01

curiousBoy


1 Answers

I had the same issue, and i found the answer using modern javascript.

The code is available here on GitHub

You can detect browser back and forward button pressed in any js app that relies on popstate / pushstate using :

// e.detail.direction will be the "backward" or "forward" String according the pressed button 
window.addEventListener('nav::user_asked_history', function(e) {
    console.log('nav::direction=', e.detail.direction); 
})

You can show / hide your own in-app back and forward buttons using :

is_nav_forward_possible()
is_nav_backward_possible()

And you can also navigate around your in-app user history using

let nav_position;
let nav_history; 

Have fun with modern JS !

like image 64
Marc Faussurier Avatar answered Jan 21 '26 19:01

Marc Faussurier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!