{

How to Check if the page is reloaded or refreshed in JavaScript


 javascript Code example Check if the page is reloaded or refreshed

Sometimes, We want to check if the page is reloaded or refreshed.

A page can be refreshed or reloaded by doing the following things.

  • keypress F5 from the user
  • page reload using location.reload()
  • back or forward button from a browser
  • Typing URL in a browser
  • or clicking a link to reload a specific page
  • Submit form
  • Prerender a page

Check if the page is reloaded or refreshed in javascript

Javascript provides a window. performance.navigation object which has supported in all the latest browsers.

window.performance.navigation provides the type of the reload

console.log(window.performance.navigation);//PerformanceNavigation {type: 1, redirectCount: 0}
console.log(window.performance.getEntriesByType("navigation")); //

Output:

PerformanceNavigation {type: 1, redirectCount: 0}
[PerformanceNavigationTiming]0: PerformanceNavigationTimingconnectEnd: 0.5connectStart: 0.5decodedBodySize: 0domComplete: 2165.699999988079domContentLoadedEventEnd: 2165.5domContentLoadedEventStart: 2165.5domInteractive: 2165.5domainLookupEnd: 0.5domainLookupStart: 0.5duration: 2165.699999988079encodedBodySize: 0entryType: "navigation"fetchStart: 0.5initiatorType: "navigation"loadEventEnd: 2165.699999988079loadEventStart: 2165.699999988079name: ""nextHopProtocol: ""redirectCount: 0redirectEnd: 0redirectStart: 0requestStart: 0.5responseEnd: 3.100000023841858responseStart: 0.5secureConnectionStart: 0serverTiming: []startTime: 0transferSize: 300type: "reload"unloadEventEnd: 0unloadEventStart: 0workerStart: 0[[Prototype]]: PerformanceNavigationTiminglength: 1[[Prototype]]: Array(0)

It returns four values 0,1,2,3 0 means the page is reloaded using form submit or loaded the first time 1 reload the page using refresh or location.reload() 2 users clicked the back and forward history buttons 3 loaded using prerender way

let data=window.performance.getEntriesByType("navigation")[0].type;
console.log(data);

output:

reload

You can also check other ways using session or cookie to store time And compare the previous timestamp with a current stamp to know that page is reloaded. However, you can not know which type causes the page to reload.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.