user1636349
user1636349

Reputation: 548

onbeforeunload event not firing in my code, but other examples work?

As usual, I want to alert users to unsaved changes when leaving a page. I have this test page:

<html>
<head>
<title>Testing</title>
<script language="JavaScript1.1" src="https://127.0.0.1:8443/scripts/base.js"></script>
<script language="JavaScript1.1" src="https://127.0.0.1:8443/scripts/edit.js"></script>
<script language="JavaScript1.1">window.onbeforeupload=moveAway</script>
</head>
<body onLoad="init()">
<a href="http://www.google.com">Google</a>
</body>
</html>

The moveAway function is defined in "edit.js" like this:

function moveAway ()
  return "foo";<br>
}

The event doesn't fire, or at least it just leaves the page silently (using IE8, Firefox 15, and Chrome 20). I've tried breakpointing the function in Firebug and it never gets to the breakpoint. I've tried it from the web server (an SSL server, the test version of which runs at 127.0.0.1:8443) and I've tried opening the file directly with the browser (which is why I used absolute URLs for the first two <script> tags). I've tried removing the "src=" attribute from the script tags.

On the other hand, this page has an example which does work (at least in Firefox):

https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

There is also a very similar example at MSDN which also works:

http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx

I really can't see the difference between what they do and what I'm doing. can anyone tell me why their code works and mine doesn't?

Upvotes: 1

Views: 1306

Answers (3)

thiagoh
thiagoh

Reputation: 7388

use jQuery bind function.. it works great for me..

see bellow

$(window).bind('beforeunload', function() { 

    return "Want to leave?";
});

Upvotes: 1

Sreenath S
Sreenath S

Reputation: 1269

onbeforeupload , really ? it should be onbeforeunload. Is that a spelling mistake, or is that how your actual code is ?

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

You have a syntax error, the function should be:

function moveAway () {
    return "foo";
}

Upvotes: 0

Related Questions