Take the 2-minute tour ×

Using a python cgi script and I have a form with both a Submit and Cancel button.

  • When a user tries to leave the web page by clicking Cancel, closing the window or hitting the back button, I want to delete a file that exists on the server. The file name is dependent on the values in the form.
  • When the user clicks the Submit button, no file will be deleted. The form action is to take the user to another python cgi script.

    I can catch the user leaving the page with javascript onbeforeunload event, but I can't delete the files in javascript. How do I delete the files?

share|improve this question
This sounds like you have a conceptional problem - why not save the file after the user submits the form? –  l4mpi Sep 24 '12 at 14:58
add comment

2 Answers

up vote 0 down vote accepted

You can't access server files using Javascript because of security reasons. However, you can make a postback in the onbeforeunload event and on the server-side event (which handles this postback) you can delete the server file(s) to be deleted.

share|improve this answer
I'm very inexperienced with web development so I need some more explanation. What do you mean by postback? Reload the existing form? What does this look like in the onbeforeunload? –  Ian Lake Sep 24 '12 at 13:43
You should use AJAX in the onbeforeunload event to request a script on the server which can then delete the file, see w3schools.com/ajax/default.asp for a simple tutorial. –  hongaar Sep 24 '12 at 13:49
You can read many tutorials about Javascript postbacks. An AJAX postback might be ideal for you. On Python (server-side) you should handle the event and delete your files. –  Lajos Arpad Sep 24 '12 at 14:01
Thank you. In my onbeforeunload method, I use AJAX to do an xmlhttprequest object to send a request to a python script on my server which deletes the files. The AJAX tutorial was very helpful. –  Ian Lake Sep 25 '12 at 17:29
add comment

As Lajos Arpad wrote, you should send notification to the server when the page is unloaded (XmlHTTPRequest in onbeforeunload event for example); but beware, that it will not be bulletproof - for example if user resets his/her machine, or forces killing browser process ungracefully (unix kill -9 for example), the browser will cease to exist and will not send any notification to the server. Maybe in that case it would be the best to introduce some heartbeat, like the webpage sends XHR every 10 seconds, and if the server doesn't see any heartbeat in 5 minutes, it's likely that user died and the file should be deleted too.

share|improve this answer
add comment

Your Answer


