0

Hi I need to distinguish between 2 events,

  1. When the page loads for the first time, I want to set some value in the header say "Welcome"

  2. Later if after loading if the user refreshes the window, I would like my Javascript to detect this as page refresh event and not mistaken as page load and set some other value in the header say "You have just refreshed the page"

Can you help in implementing this?

ks_baba
  • 29
  • 3
  • 11

2 Answers2

2

As this answer states, you can use cookies. When the page is refreshed, this function will check if the cookie exists or not. If it doesn't, the function will set a cookie. If the cookie does exist, then the function will alert "You refreshed!".

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // cookie doesn't exist, create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // not first visit, so alert
    alert('You refreshed!');
  }
}

and in your body tag, put:

<body onload="checkFirstVisit()">

EDIT: To make sure that if a user leaves the page and then re-enters it without closing and opening the browser in between, you can use some onunload event to clear the cookie.

Community
  • 1
  • 1
416E64726577
  • 2,214
  • 2
  • 23
  • 47
1

If you don't have to support old browsers, I suggest to use localStorage:

if (localStorage.getItem("visit") == null)
{
    // Show Welcome message
    $('body').append("<h1>Welcome, guest!</h1>");
}

localStorage.setItem("visit", new Date());
// Here you can check if last visit date is longer than a day and clear it up, showing Welcome message again...

Fiddle.

Can I use Web Storage?

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105