Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle refresh page event with javascript

Is it possible to use javascript to handle the event of refreshing page? What i want is get notice if user do one of these behaviours:

  • refresh page by pressing F5
  • close tab or browser
  • enter a new url then press enter on browser

to display a warning message?
Thanks in advance!

like image 456
tiboo Avatar asked Oct 16 '10 17:10

tiboo


People also ask

How do you refresh a page using JavaScript?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

Can refresh the webpage in JavaScript by using?

Location. reload() method is used to refresh the webpage in javascript.

How do you call a function on page refresh?

You need to call myFunction() when the page is loaded. window. onload = myFunction; If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.


1 Answers

You don't want the refresh, you want the onbeforeunload event.

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

Sample code from article

<HTML> <head> <script> function closeIt() {   return "Any string value here forces a dialog box to \n" +           "appear before closing the window."; } window.onbeforeunload = closeIt; </script> </head> <body>   <a href="http://www.microsoft.com">Click here to navigate to        www.microsoft.com</a> </body> </html> 
like image 169
Lou Franco Avatar answered Sep 21 '22 02:09

Lou Franco