Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask confirmation when closing a window?

Tags:

javascript

I want to pop up a message asking for confirmation if the user wants to leave the current page, exactly like stackoverflow does it when you are typing a question.

Could someone help me on this, by giving me a script or redirecting me to an answer (on this site or elsewhere) ?

Thanks

like image 246
Maxime ARNSTAMM Avatar asked Dec 18 '22 03:12

Maxime ARNSTAMM


2 Answers

You could use the onbeforeunload event.

window.onbeforeunload = function() {
   return 'Are you sure that you want to leave this page?';
};
like image 147
Jacob Relkin Avatar answered Dec 19 '22 16:12

Jacob Relkin


You need to handle the window's onbeforeunload event and return a confirmation message as a string.

onunload will not work here. Demo

like image 44
SLaks Avatar answered Dec 19 '22 17:12

SLaks