Ahmed
Ahmed

Reputation: 3043

Check if page gets reloaded or refreshed in JavaScript

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.

Upvotes: 302

Views: 616094

Answers (16)

JonT
JonT

Reputation: 95

Based on Илья Зелень answer but works in Safari (Mac and iOS).

This version uses both the depricated performance.navigation.type api and the new performance.getEntriesByType('navigation'), but defaults to the performance.navigation.type because of Safari. In time of writing (2024), Safari still has a bug (2024) where "reload" is returned from window.performance.getEntriesByType('navigation') when a user navigates backs to the page (clicks the "back" button). Safari behaves correctly, however, for performance.navigation.type.

const isPageReloaded = (
    window.performance.navigation 
    ? (window.performance.navigation.type === window.performance.navigation.TYPE_RELOAD)
    : window.performance
      .getEntriesByType('navigation')
      .map((nav) => nav.type)
      .includes('reload')
);

console.log("isPageReloaded: ", isPageReloaded);

Upvotes: 0

btx
btx

Reputation: 2497

This implementation helped me:

From MDN reference 2022: Navigation Timing Level 2 specification

/** @var PerformanceNavigationTiming */
const navigationEntry = window.performance.getEntriesByType('navigation')[0];
const navigationType = navigationEntry.type;

const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForwarad = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';

Upvotes: 2

Silvio Guedes
Silvio Guedes

Reputation: 1274

In JavaScript (2023):

if (window.performance.getEntriesByType) {
    if (window.performance.getEntriesByType("navigation")[0].type === "reload") {
        alert("reloaded");
    }
}

Upvotes: 1

Илья Зелень
Илья Зелень

Reputation: 8108

New standard 2018-now (PerformanceNavigationTiming)

window.performance.navigation property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead.

PerformanceNavigationTiming.type

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Check if page gets reloaded or refreshed in JavaScript

const pageAccessedByReload = (
  (window.performance.navigation && window.performance.navigation.type === 1) ||
    window.performance
      .getEntriesByType('navigation')
      .map((nav) => nav.type)
      .includes('reload')
);

alert(pageAccessedByReload);

Support on 2021-11-09

Table of support

Support on 2023-07-19

Table of support 2023-07-19

The type read-only property returns a string representing the type of navigation. The value must be one of the following:

  • navigate — Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below.

  • reload — Navigation is through the browser's reload operation or location.reload().

  • back_forward — Navigation is through the browser's history traversal operation.

  • prerender — Navigation is initiated by a prerender hint.

This property is Read only.

The following example illustrates this property's usage.

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);
 
    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));
    
    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

Upvotes: 127

Avatar
Avatar

Reputation: 15194

One easy solution has not been mentioned (not relying on the deprecated window.performance.navigation):

  1. Use window.onbeforeunload to store the time and the URL of your current page (in localstorage) when the user leaves the page (potentially refreshes the page).

    window.onbeforeunload = function(e)
    {
        localStorage.setItem('reload-url', window.location.href);
    }
    
  2. Then use window.onload to get those values from localstorage.

    window.onload = function(e)
    {
        if (localStorage.getItem('reload-url') != null))
        {
            if (window.location.href == localStorage.getItem('reload-url'))
            {
                console.log('Reload');
            }
        }
    }
    
  3. If the recent URL matches the stored URL and if the stored time matches the current time (maybe with a tiny offset) then it is a page reload by the user.

Upvotes: 2

sam ruben
sam ruben

Reputation: 385

Append the below script in the console:

window.addEventListener("beforeunload", function(event) {
     console.log("The page is redirecting")
     debugger;
});

Upvotes: 0

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11096

I have written this function to check both methods using the old window.performance.navigation and the new performance.getEntriesByType("navigation") at the same time:

function navigationType(){

    var result;
    var p;

    if (window.performance.navigation) {
        result=window.performance.navigation;
        if (result==255){result=4} // 4 is my invention!
    }

    if (window.performance.getEntriesByType("navigation")){
       p=window.performance.getEntriesByType("navigation")[0].type;

       if (p=='navigate'){result=0}
       if (p=='reload'){result=1}
       if (p=='back_forward'){result=2}
       if (p=='prerender'){result=3} //3 is my invention!
    }
    return result;
}

Result description:

0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.

1: Clicking the Reload button or using Location.reload()

2: Working with browser history (Back and Forward).

3: prerendering activity like <link rel="prerender" href="//example.com/next-page.html">

4: any other method.

Upvotes: 15

nPcomp
nPcomp

Reputation: 9973

If

event.currentTarget.performance.navigation.type

returns

0 => the user just typed in an URL
1 => the page reloaded
2 => the back button is clicked.

Upvotes: 9

DitherSky
DitherSky

Reputation: 1110

The first step is to check sessionStorage for some pre-defined value and if it exists, alert the user:

if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');

The second step is to set sessionStorage to some value (for example true):

sessionStorage.setItem("is_reloaded", true);

Session values kept until the page is closed, so it will work only if the page reloaded in a new tab with the site. You can also keep a reload count the same way.

Upvotes: 45

Rahul Jain
Rahul Jain

Reputation: 3141

⚠️⚠️⚠️ window.performance.navigation.type is deprecated. Please see Илья Зеленько's answer.


A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.

It uses the Navigation Timing API.

//check for Navigation Timing API support
if (window.performance) {
  console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
  console.info( "This page is reloaded" );
} else {
  console.info( "This page is not reloaded");
}

Source: Navigation Timing API

Upvotes: 280

techfoobar
techfoobar

Reputation: 66693

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()">

Upvotes: 17

VoronoiPotato
VoronoiPotato

Reputation: 3183

I found some information in JavaScript Detecting Page Refresh. His first recommendation is using hidden fields, which tend to be stored through page refreshes.

function checkRefresh() {
    if (document.refreshForm.visited.value == "") {
        // This is a fresh page load
        document.refreshForm.visited.value = "1";
        // You may want to add code here special for
        // fresh page loads
    } else {
        // This is a page refresh
        // Insert code here representing what to do on
        // a refresh
    }
}
<html>

<body onLoad="JavaScript:checkRefresh();">
    <form name="refreshForm">
        <input type="hidden" name="visited" value="" />
    </form>

</body>

</html>

Upvotes: 8

Vasukipriya K N
Vasukipriya K N

Reputation: 59

 document.addEventListener("keydown", (e)=>{
   if (e.keyCode === 116) {
     e.preventDefault();

      // your code here
      // var r = confirm("Reload!");
      // if (r == true)
      //  window.location.reload();
   }
 })
  1. Here we used event listener 'keydown' because F1 - F12 keys are not available on browsers for 'keypress'.
  2. 116 is the keycode for 'F5'. Check here
  3. 'preventDefault()' will stop the default function of the key pressed. Here it stops direct refresh when F5 is pressed.
  4. Then add your code.
  5. When the alert is confirmed, 'location.reload()' will reload the page

Upvotes: -5

user13575758
user13575758

Reputation:

<script>
    
    var currpage    = window.location.href;
    var lasturl     = sessionStorage.getItem("last_url");

    if(lasturl == null || lasturl.length === 0 || currpage !== lasturl ){
        sessionStorage.setItem("last_url", currpage);
        alert("New page loaded");
    }else{
        alert("Refreshed Page");  
    }

</script>

Upvotes: -1

Mointy
Mointy

Reputation: 575

Here is a method that is supported by nearly all browsers:

if (sessionStorage.getItem('reloaded') != null) {
    console.log('page was reloaded');
} else {
    console.log('page was not reloaded');
}

sessionStorage.setItem('reloaded', 'yes'); // could be anything

It uses SessionStorage to check if the page is opened the first time or if it is refreshed.

Upvotes: 3

Alexis Gatuingt
Alexis Gatuingt

Reputation: 547

if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


Upvotes: 0

Related Questions