One question:
How do i differentiate when a page is refreshed event from a page/browser closed event?
Because it seems that the onbeforeunload event is triggered when a page is refreshed and when it's closed, and i didnt want that to happen ?

Member Avatar for diafol

I don't think it's possible to distinguish between these events. WRT refresh are you talking about the browser button / F5? If so, I can't see how you'd trap this event. If the refresh is via webpage link, you probably could stop the onbeforeunload event before completing the page refresh.

Don't take my view as the gospel truth though.

Member Avatar for diafol

Here's some code I slapped together to show how to prevent the onbeforeunload:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>

<a href="crap.php" class="goodLink">BUG OUT FOR REAL</a><br />
<a href="crap2.php" >ASK ME</a><br />
<a href="crap3.php" class="goodLink">DEFINITELY BUG OUT</a><br />

<form method="post">
    <button class="goodLink">BUTTON: DON'T CHALLENGE ME</button><br />
    <button>BUTTON: OK ASK ME NICELY</button><br />
    <input type="submit" class="goodLink" value="SUBMIT: DON'T CHALLENGE ME" /><br />
    <input type="submit" value="SUBMIT: ASK ME NICELY :)" />    
</form>

<script language="JavaScript">
var popup = true; //default action is to popup
window.onbeforeunload = function(e){
    if(popup == true)return "Wanna leave?";
}
$('.goodLink').click(function(){
    popup=false;
}); 
</script>
</body>
</html>

I have no idea whether this helps at all?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.