2

I want to prevent a user from leaving my site while their file is being uploaded to my server. So I can send an alert message to a user using this javascript...

 window.onbeforeunload = function() {
       return "Your files are not completely uploaded...";
 }

The issue I’m having is that after the file upload is complete I don’t want to prevent user navigation. So essentially I want to have the alert message pop up only when the user is trying to leave the site while their file is uploading. I can console.log(“file upload is complete”) when the file is completely uploaded so I know where I should be stopping this event but I’m not sure what the code should look like. Any help is greatly appreciated.

Nodedeveloper101
  • 421
  • 1
  • 9
  • 24
  • 1
    `window.onbeforeunload = null;` should do the trick. Notice also, that a message returned from onbeforeunload handler won't be shown in all browsers. – Teemu Nov 30 '15 at 17:46

3 Answers3

1

Just put a flag and check it in beforeunload, set it to true on upload and to false on finish.

 window.onbeforeunload = function() {
       if (prevent_leave) {
           return "Your files are not completely uploaded...";
       }
 }
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

You can check using jQuery form plugin. File upload progress bar with jQuery

It provides you to get the percentage of file uploaded and by checking it (whether it has completed or not with 100%) you can show an alert message to user.

Community
  • 1
  • 1
Lovey
  • 880
  • 3
  • 15
  • 31
-1

I have put this javascript in the function where the user first uploads the file...

window.onbeforeunload = function() {
       var prevent_leave = true;
       if (prevent_leave) {
           return "Your files are not completely uploaded...";
       }
 }

then I have put this javascript after the file was completed..

 window.onbeforeunload = function() {
       var prevent_leave = false;
       if (prevent_leave) {
           return "Your files are not completely uploaded...";
       }
 }

And this works as I expected too. Thanks @jcubic

Nodedeveloper101
  • 421
  • 1
  • 9
  • 24
  • Why would you declare those variables? The upper if statement will always result in a true and the lower always with a false. – melledijkstra May 05 '18 at 21:35