Friday, June 15, 2012

How to detect page refresh using Javascript

Today I'm going talk about how to detect a page reload/refresh using Javascript. It can be done using server side scripts, but I find that Javascript is the easiest method to do this. This is how I go about it:

First, we need a form to detect the page reload. If you have a form in your page, you can use the same, or in case that you don't have/use a form on your page, you can simply create one and set its CSS visibility to hidden, so that it doesn't unnecessarily show up on the page.

This is what you need to add to your HTML:

<body onLoad="refreshCheck()">
 Your website content here
 
</body> 

The necessary Javascript that is to be added is:

function refreshCheck()
{
 if( document.refresh.visited.value == "" )
 {
  // Page loaded for first time
  document.refresh.visited.value = "1";
  alert("Fresh!!");
 }
 else
 {
  // On page refresh
  alert("Refresh!!");
 }
}

That's it! You can handle the events as you want instead of the alerts ;)

4 comments:

  1. Hi Gautam, I tried this javascript but it is giving error, mentioning that visited value is of type color. not working with string value. Could you please test this?

    ReplyDelete
  2. Hello Khushi, can you give me a little more information on this? Did you try the code as it is, or modified it? What browser are you using?

    ReplyDelete
  3. Nice, but it is always giving me the alert with message 'fresh'...

    ReplyDelete
  4. Hi, is there any methods to detect the browser/tab close by alert "page closed" and browser refresh by alert "refresh"

    ReplyDelete