Search code examples
javascriptalertonbeforeunload

Javascript and onbeforeunload?


I have

<span class="cssButton"><a href="javascript:void(0);" class="buttonBlue" onclick="swfu.startUpload();"> <img src="http://uber-upload.com/img/icons/up_16.png" alt=""/> Uber-Upload! </a></span>

And i want to make it so that if you press that button, it also sets a variable that makes it so that if you try to leave the page, it will pop up one of those "Are you sure you want to leave this page" alerts to prevent people from accidently leaving while there is an upload going on.

Dont worry about unsetting the variable after the upload finishes, i'll add that, i just need one of you smart coders to make me a framework.

Thanks!


Solution

  • Add this declaration to the page:

    var upcount = 0;
    

    Change your onclick to:

    onclick="++upcount; swfu.startUpload();"
    

    If the swfu gives you some kind of event when it's done uploading, put this on it:

    --upcount;
    

    And add this handler:

    window.onbeforeunload = function() {
        if (upcount > 0) {
            return "The upload is still in progress, leaving the page will cancel it.";
        }
    }
    

    Where browsers respect the onbeforeunload, that'll work. And most of them do, most of the time. Where they don't, well, you tried. Note that by using a counter, you're allowing for multiple uploads.

    You might consider attachEvent (IE) or addEventListener (standard) (or a library like Prototype or jQuery that evens out the differences for you) for attaching your events rather than using attributes. Using attributes (aka DOM0 handlers) is fairly old-fashioned and a bit limiting (only one handler per event per element). But it does still work.