The onbeforeunload event occurs when the document is about to be unloaded.
This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.
You can use this event as per your need using following approaches mentioned below:
In HTML,
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <body onbeforeunload="return yourFunction()"> <script> function yourFunction() { return "Your custom message."; } </script> </body> </html> |
In Javascript,
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <body> <script> window.onbeforeunload = function(event) { event.returnValue = "Your custom message."; }; </script> </body> </html> |
In JavaScript, using the addEventListener() method,
1 2 3 4 5 6 7 8 9 10 11 |
<!DOCTYPE html> <html> <body> <script> window.addEventListener("beforeunload", function(event) { event.returnValue = "Your custom message."; }); </script> </body> </html> |
Thanks