How do I prevent users from closing a page until upload is finished?

If a user is uploading a large file using the Uploadcare widget and refreshes/closes their page, the upload may stop, and we lose the file. How to prevent this?

You could use the window.onbeforeunload event while a file is uploading to display a pop-up if a user tries to close the page.

image

Once uploaded, you can disable it. This code works for single file uploads.

const widget = uploadcare.Widget('[role=uploadcare-uploader]');
widget.onDialogOpen(dialog => {
  dialog.fileColl.onAdd.add(() => {
  // Some browsers doesn't allow custom messages
  // and display default text instead (see image above)
  window.onbeforeunload = () => 'Are you sure you want to leave the page?';
  });
  dialog.fileColl.onAnyDone(() => {
    window.onbeforeunload = undefined;
  });
});