window.onbeforeunload javascript code

Some time you can come around a situation that you want to confirm your users about their action when they are navigating away from your page or want to close this page.

This may be a scenario of useful data transaction or a online chat system or in case youe users are editing a document and need to save it before exit.

The event which is invoked when users navigate away from a web page is onbeforeunload.
Yeah it is on before unloading the page.

So you can ask your users about their actions if they tries to navigate away or close the window by this simple and small code snippet.

<script type=”text/javascript”>

window.onbeforeunload = askUser ;

function askUser(){
  return “The changes you made will be loast if you navigate away from this page”;



Put this script in your webpage and see the code in action.

This feature you can also find in

Window.onbeforeunload picture