0

When the page loads I set: var lock = 0;

I change lock to 1 if I want to provide a warning to the user if they are about to close their page and have pending actions. I sometimes change it to 2 if I need a different warning. If lock is set to 0 then I don't want a warning message to appear as the user closes their page.

This shows my custom warning message just fine every time the user moves away from the page, regardless of lock setting.

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

This only shows when lock is 1 or 2 but doesn't show my custom warning message.

window.onbeforeunload = function(){
if(lock == 1) return 'Are you sure you want to leave this page?';
else if(lock == 2) return 'Bad things will happen if you close this page!';
}

Is there a way to have a conditional custom warning message? It seems like if I have anything other than 'return' inside the function then it uses the default message.

GFL
  • 1,278
  • 2
  • 15
  • 24
  • you cant show a custim message in at least firefox - other browsers your mileage may vary – Jaromanda X Sep 07 '16 at 03:02
  • This is arguably a dupe: http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own?rq=1 – wally Jan 03 '17 at 09:33

1 Answers1

3

Tarting from Chrome 51, A window’s onbeforeload property no longer supports a custom string.

Reference: https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove-custom-messages-in-onbeforeload-dialogs

Lutreer
  • 31
  • 4
  • "Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." See bug 588292 and Chrome Platform Status." - https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – wally Jan 03 '17 at 09:31