Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jackie Jen
Jackie Jen
2,723 Points

How 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

Jackie Jen
Jackie Jen
2,723 Points

Hi 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?

Greg Kaleka
Greg Kaleka
39,018 Points

Not 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
Jackie Jen
2,723 Points

This 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