Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJackie Jen
2,723 PointsHow to detect back button, refresh button, F5, Ctrl+R in javascript
When i detect the action of back button, refresh button, F5, Ctrl+R is click, i want to perform a function using javascript instead of just return some message.
I have google and just able to detect on F5 & Ctrl+R event is click. How can i detect the back button and refresh button been click?
2 Answers
jcorum
71,830 PointsYou might want to take a look at this: http://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser
Greg Kaleka
39,021 PointsNot sure about the back button, but as described in this StackOverflow post, you can use window.onbeforeunload
to detect refresh (either F5, CTRL+R or the browser's button).
Try popping this into the console in Chrome:
window.onbeforeunload = function() {
return "Dude, are you sure you want to refresh? Think of the kittens!";
}
The problem with this is it detects any attempt to leave the page, including closing the tab/window or even clicking a link, so it very well may not fit your use case. Not entirely sure you can specifically detect a refresh, though.
Edit: Here's a simplistic (read: needs work) workaround that will ignore link clicks.
Jackie Jen
2,723 PointsThis window.onbeforeunload can detect the page is whether refresh but not all browser can be detected. Beside that this function only able to return a msg.
The best way is using cookies to detect if the user is trying to refresh http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
Jackie Jen
2,723 PointsJackie Jen
2,723 PointsHi jcorum,
Thanks for reply, i have read through it and try it out. But still dun get what it mean. Could you please explain more detail with an example?