Reputation:
i m creating a web application, after login user navigates to home page where i have a navbar(Links to pages/url).Navbar is like this Home-Nvigates to home page Profile-Navigates to profile page Chat-navigates to chat page when user clicks on chat link . I want that when user closes the browser window ,accidentally or manually he should get an alert for that i have used onbeforeunload function like this
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
Now when i m closing the browser on chat page i m getting following alert "You have attempted to leave this page." that is working fine,but now the main problem is that when i m clicking on other links like Profile or Home this function is called and me geting this alert even though i have implemented this code in chat.jsp .Even i m refreshing this page i m getting this alert mentioned above which i should get only when i closes widow of chat.jsp page rather than other pages or Refresh.Plese help
Upvotes: 1
Views: 882
Reputation: 14051
Onbeforeunload fires when the page is unloading be it by refresh, navigate or page close. You could add an onclick eventhandler to anchors on your page that remove your onbeforeunload event to avoid it and you might be able to do the same with an onkeydown event on the window/body/page however I don't believe there's a way to catch users pressing the browser's refresh button.
example:
<html>
<head>
<script type="text/javascript">
function warnUnload(){
return "Your message here...";
}
function linkNavi(){
window.onbeforeunload = null;
}
function isRefresh(e){
var key = null;
if(window.event) // IE
key = e.keyCode;
else if(e.which) // Netscape/Firefox/Opera
key = e.which;
if(key == 116) //F5
window.onbeforeunload = null;
}
window.onbeforeunload = warnUnload;
window.onkeydown = isRefresh;
</script>
</head>
<body>
<a href="http://google.com">Google</a>
<a href="/" onclick="return linkNavi();">Home</a>
</body>
</html>
Upvotes: 3