Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: onrefresh or onreload?

Tags:

javascript

I want an event handler that fires when the user hits reload. Is onrefresh or onreload the correct handler to add to ? Also, will this even fire before or after onunload? Are there an browser inconsistencies? Thanks.

like image 370
Sam Lee Avatar asked Apr 10 '09 19:04

Sam Lee


2 Answers

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.

like image 168
Rex M Avatar answered Sep 21 '22 22:09

Rex M


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

like image 35
tyler_mitchell Avatar answered Sep 20 '22 22:09

tyler_mitchell