Below is the general coding. You can modify the code with your own logic and requirements.
return "Any output here forces a dialog box to \n" +
"appear before closing the window.";
window.onbeforeunload = callIt;
/* This is for page refresh */
<a href="http://www.abhijitpal.in">Click here to navigate to