14

I have a form that when filled in, I can exit the window without being given a warning (I'm using Chrome).

How can I ensure I get a warning before exiting? Is there a Django setting for this?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • 3
    sounds more like JS territory. – Ashish Acharya Aug 04 '18 at 01:21
  • Django is server side. It doesn’t know what form data has or hasn’t been entered by a user until the form is submitted. This is a client side problem, and would require JavaScript. – fubar Aug 04 '18 at 01:29
  • JavaScript on close alert – Scath Aug 04 '18 at 01:39
  • Does this answer your question? [Best way to detect when a user leaves a web page?](https://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page) – ggorlen Jan 04 '20 at 13:52

2 Answers2

20

You need to supply a function returning a string to onbeforeunload of the window or the document body in order to trigger the "Leave site" popup.

window.onbeforeunload = () => '';
<a href="http://example.com">Click to trigger</a>
davidchoo12
  • 1,261
  • 15
  • 26
  • Getting this error when I paste in my js file: https://i.imgur.com/RzGwvyt.png any idea? – Zorgan Aug 04 '18 at 02:51
  • Nevermind it is working. However are you able to tell me how I can only summon the popup when the form is not empty? currently it pops up every time I navigate away from any page... – Zorgan Aug 04 '18 at 02:52
  • You can add a condition to check if any of the form input is empty then return a string else return null – davidchoo12 Aug 05 '18 at 13:02
  • Probably you had that because your editor does not support arrow functions. In my editor, for example, I can choose compatible javascript standard. I assume you have something similar. – Sharikov Vladislav Oct 29 '21 at 06:14
3

The event is called beforeunload, so you can assign a function to window.onbeforeunload

Scath
  • 3,777
  • 10
  • 29
  • 40