Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event?

Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event?

So simply put, the user clicks the browser back button, and instead of being taken back to the previous page on my site, my function fires. My aim is not to to prevent the user leaving my site.

Something like the below pseudo code:

window.backbutton.click(function(e){ preventDefault(e); myFunc(); })

FYI What I actually have is an internal back/forward system controlled by buttons within the view and I'd like to trigger my buttons when user clicks browser back.

like image 776
Aaron Avatar asked Jan 28 '26 18:01

Aaron


1 Answers

You should look into Browser History https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history . It is a new standard for emulating pages (back and forward) on a single-page site.

like image 89
Kyle Avatar answered Jan 31 '26 09:01

Kyle



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!