1

I have a page where a user can upload a bunch of files as part of a form. The files are uploaded to the cloud with each addition. If they cancel the form, the files are deleted from the cloud. If they refresh the page or close the browser before completing, I would also like to delete those files from the cloud. Is it possible to hook into these events?

Musical Shore
  • 1,361
  • 3
  • 20
  • 41
  • 1
    It's possible, both the `window.onunload` and `window.onbeforeunload` events are available, but they aren't very reliable, and if the browser is already uploading, chances are you won't be able to abort the request and send a new request telling the server to delete files, before the browser closes. – adeneo Dec 02 '15 at 21:28

3 Answers3

2

The same way ytou have onload when the page load, you have unload when you, well, unload.

If you want to add an message before that, onbeforeunload seems to do the trick:

<html>
<body onunload="javascript:alert('Beep!');" onbeforeonload="javascript:return confirm('I beep first. Continue?');">
Close me for an alert
</body>
</html>

*Disclaimer: This is a terrible example, do not inline javascript.

Community
  • 1
  • 1
Martijn
  • 15,791
  • 4
  • 36
  • 68
1

You are looking for window.onunload = myFunciton: http://www.w3schools.com/jsref/event_onunload.asp

Execute a JavaScript when a user unloads the document:

<body onunload="myFunction()"> 
CoderPi
  • 12,985
  • 4
  • 34
  • 62
0

You want something like this:

window.onbeforeunload = handler;

In the handler itself you also can return some string that is shown in the resulting alert box (which is always displayed by the browser, you cannot control that). However the return value does not work in Firefox which will ignore your message. Also note that you only can have one beforeunload handler.

frontend_dev
  • 1,693
  • 14
  • 28