Alex Rivera | Logout

Check if page gets reloaded or refreshed in JavaScript

Asked 2011-02-15T14:39:02.883
310

I want to check when someone tries to refresh a page.

For example, when I open a page nothing happens but when I refresh the page it should display an alert.

Edit
Report

1 Answer

18

Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.

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

And in your body tag:

<body onload="checkFirstVisit()">
answered 2011-12-20T07:25:23.497

Your Answer