Check if page gets reloaded or refreshed in JavaScript
Asked Answered
V

15

291

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.

Villainy answered 15/2, 2011 at 14:39 Comment(4)
Not really possible without server side code. What do you need it for? Maybe if you give the bigger picture we can suggest better alternative.Bloodsucker
Maybe you could do such as thing with a cookie... like storing the time and on reload compare the time difference.Dashing
I want to make such as facebook link will be #!/anythinge I want to remove #! when page reload onlyVillainy
@Villainy I am trying to do the same thing. Did any of the solutions below work for you?Lh
V
276

⚠️⚠️⚠️ 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

Vintager answered 6/4, 2016 at 7:20 Comment(13)
thanks buddy this is accurate solution to detect either the page is reloaded from right click/refresh from the browser or reloaded by the url.Peptonize
Be aware.Chrome had recently change this behavior. When user click current address bar and hit enter, the value of performance.navigation.type will be 1 which should be 0. I tested in Version 56. Not sure why.Imalda
It still works in Firefox 52 but not in Chrome 57. Reloading by clicking on reload button or by putting cursor in address bar and hitting enter both return performance.navigation.type value of 1.Androsterone
Recently tested in chrome 57 but it worked fine as always. I was not able to reproduce the issue you were having.Vintager
In react with redux performance.navigation.type === 1 occur multiple times- unwanted behavior. so window.onload resolve the problemSurface
This does work for refresh, but also triggers during any AJAX requests, so it was not what we wanted.Extremism
Does not work with the "Run code snippet" feature (because the snippet runs in an iframe), but works in Chrome with the following reload methods: browser reload button, enter key in the URL bar, right mouse click/reload.Elicia
They way it works is as expected, any interaction with the page which force a new navigation state to the same page is considered a refresh. So depending in your code this is extremely useful, either to register every time the page has been refreshed, reloaded or any ajax interaction. I can give this a lot of uses for functionalities and analytics.Bangui
performance.navigation.type == performance.navigation.TYPE_RELOAD is easier to read instead of == 1. Also, if you check performance.navigation you will find that there are 4 diffrent navigation types like TYPE_BACK_FORWARD,TYPE_NAVIGATESerenata
Shouldn't the 2nd if and the else be inside the first one?Marketing
navigation is now deprecated, is there a modern way to do this?Smectic
Even while closing a browser's tab, performance.navigation.type gives you 1 (performance.navigation.TYPE_RELOAD)! Can we actually detect the browser is about to refresh?Oquassa
Above code is not working while reloading page using 'F5' key.Pember
V
120

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);
  }
}
Veach answered 14/11, 2018 at 19:35 Comment(8)
+1 for pointing out the deprecated API, but -100 to Apple for their lack of support in iOS still into 2020Tocantins
Thanks for pointing that out. So here's the full compatible solution: jsfiddle.net/j9o1khcw/2Kerby
@0nline I tried your solution and it did not work for me FYI.Jacalynjacamar
@Jacalynjacamar Try it outside jsfiddle or in your devtoolsKerby
So does this work on Safari in 2022? I don't have a Safari browser.Depressant
In first snippet: It would call window.performance.getEntriesByType() every time window.performance.navigation.type === 1 is false. Not sure if this is intended or not.Fortyniner
@Илья Thanks for pointing it out. It is a big help for me. I've a question. I tested various ways but always got just one entry returned by getEntriesByType('navigation'). What is your reason to use .map instead of directly using the first entry. Is it possible to get multiple entries in some scenarios? I'm interested to know more about it. Please explain.Le
Where is the actual solution? I couldn't post this question because this thread supposedly holds the answer. Where is it though? Where is the answer on how to catch a user refreshing the browser page?Acrefoot
G
44

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.

Gallican answered 25/7, 2013 at 10:22 Comment(6)
Two things to be aware of: 1). You can only store string values in session and local storage. Therefore true is converted to "true". 2). Session storage persists until the user closes the browser window, so you can't tell the difference between page reload and navigating away from and back to you site within the same browser session.Johanajohanan
SessionStorage can be modified from within browser? Correct me if I'm wrong. Someone can add/delete the key and your logic/code can be circumvented.Diadiabase
Note that sessionStorage restore if you close tab and restore it from ctrl+shift+T That may be potentially hole in secure in public place when need clean session tokenMindszenty
this does not cover page turn vs. page reloadAlvertaalves
@kuzroman, seems to be working fine, even when reopened after closingHamm
To avoid any discussion, clear the variable before step 2. sessionStorage.removeItem("is_reloaded") and then, set it again sessionStorage.setItem("is_reloaded", true);Romain
S
17

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()">
Seringapatam answered 20/12, 2011 at 7:25 Comment(8)
What about returning users?Backman
Like @Rob2211 says this only checks if the page has been visited and can give a false positive as long as the page is revisited when the cookie is still alive. Do not use this to check refresh.Pustulant
@Pustulant - The cookie is a created without any expires value and will be destroyed when the browser is closed.Seringapatam
@Seringapatam nice catch. Wouldn't this still pose a problem if the user revisits the site before that cookie is destroyed?Pustulant
@Pustulant - Yes, if the browser is left open and the user re-visits after some time, it will not be considered as a new visit.Seringapatam
This suffers the same drawbacks as the session storage solution.Bobbie
I have rolled back the edit that says document.cookies is obsolete. It’s not obsolete; this suggested edit has been approved with one reject vote that says “It says that document.cookie is obsoleted, but provides no documentation or link.”Serendipity
this does not cover page turn vs. page reloadAlvertaalves
A
15

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.

Ailurophile answered 10/3, 2019 at 11:38 Comment(1)
this is not working in safari. the returned array is empty.Asafoetida
P
9

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.

Pleuropneumonia answered 2/2, 2017 at 21:56 Comment(3)
I got this error, can you explain it more? Uncaught TypeError: Cannot read property 'currentTarget' of undefinedMylo
2 => TYPE_BACK_FORWARD The page was accessed by navigating into the history. developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationSesqui
performance.navigation.type is deprecated, pls see my answer.Leucocyte
R
8

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>
Rufinaruford answered 15/2, 2011 at 14:43 Comment(7)
We can also check by checking Referer property and modify server response on the basis of this propertyErring
Side note: the first method listed on that page will fail because the code is executing before the DOM has been parsed. Moving the <script> element to the bottom would work - but it's still not a guaranteed solution (and neither is the cookie method).Lawson
@Adeel: checking Referer isn't reliable either; many proxies and browser extensions strip it from requests.Lawson
@Rufinaruford Please try to summarize the information instead of only posting a link.Hippocrene
@AndyE he has the javascript fire on the body load, I highly doubt that will execute before the dom has loaded....Rufinaruford
For me, it always executes "if" condition and never executes "else" part, doesn't matter that whether I did page load or page refresh.Timothytimour
On Chrome I get Uncaught TypeError: Cannot read property 'visited' of undefined.Aubreyaubrie
M
3

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.

Moult answered 18/8, 2020 at 23:14 Comment(1)
Does not work when re-opening a tab using ctrl/cmd+TAnthracosis
B
2

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.

Barbarese answered 13/10, 2022 at 14:28 Comment(0)
A
2

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';
Alvertaalves answered 27/10, 2022 at 10:50 Comment(5)
This is TypeScript, the OP wants the answer in JavaScript.Permute
@SilvioGuedes my apologies, code updatedAlvertaalves
Code deprecated since 2018.Mangonel
@OlivierC There is no deprecation notice on them MDN page, and the article seems to be very much up to date. Please provide a source for your info, thx!Alvertaalves
@btx: Indeed, mea culpa, I confused it with Performance.navigation. If you edit your message I will modify my note.Mangonel
P
1

In JavaScript (2023):

if (window.performance.getEntriesByType) {
    if (window.performance.getEntriesByType("navigation")[0].type === "reload") {
        alert("reloaded");
    }
}
Permute answered 27/9, 2023 at 21:15 Comment(0)
P
0
if(sessionStorage.reload) { 
   sessionStorage.reload = true;
   // optionnal
   setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
   sessionStorage.setItem('reload', false);
}


Priesthood answered 2/1, 2020 at 10:53 Comment(1)
this does not cover page turn vs. page reloadAlvertaalves
J
0

Append the below script in the console:

window.addEventListener("beforeunload", function(event) {
     console.log("The page is redirecting")
     debugger;
});
Jaquiss answered 18/11, 2020 at 6:35 Comment(1)
even adding load will do a quick check if page is reloaded or notMarsden
S
-1
<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>
Sheepdog answered 12/10, 2020 at 15:15 Comment(0)
G
-5
 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
Govern answered 24/7, 2021 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.