Javascript: onrefresh or onreload?

I don't think there are events called onrefresh or onreload. You can know when the page is unloading, but knowing why (i.e. where the user is going next) is outside JavaScript's security sandbox. The only way to know whether the page has been reloaded is to know where the user was on the last page request, which is also outside the scope of JavaScript. You can sometimes get that via document.referrer, but it relies on the browser's security settings to permit access to that information.


The WindowEventHandlers.onbeforeunload event handler property contains the code executed when the beforeunload is sent. This event fires when a window is about to unload its resources.

window.onbeforeunload = function () {
   return 'Are you sure you want to leave?';
}

This will show a confirm dialog to the user with the message you returned in your function. It will give the user a leave this page or cancel option.

There is no way around the confirm as it could be used for malicious reasons.

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload


If you combine setting a cookie with a for the specific page, with a check for the onload event, you can simulate the nonexistent event you seek. You might adjust the cookie expiration so that a reload is counted only if the initial onload was a certain time interval ago.

Tags:

Javascript