-1

Well, in order to be able to detect the status of browsers, if users are on the site, I want to send a request if they close the browser and change a feature in a model. It should be noted that this model is different from the user model in Django.

Also, I'm using Django sessions and SESSION_EXPIRE_AT_BROWSER_CLOSE=True but that's not working. So I use React window.onblur event and that's not working again!

I try this code in react but it's not working!

   let stid:string|null=localStorage.getItem('stationid')
   useEffect(() => {
     window.onblur=()=>{
       console.log('hello')
       Api.delete(STATION_ID(stid)).then((res)=>{
           console.log(res.data)
       }).catch(err=>{
         console.log(err)
       })
     }
     return () => {
         console.log('hello')
     }
   }, [])
Ammar
  • 1
  • 1
  • Does this answer your question? [Detect browser or tab closing](https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing) – David Aug 29 '23 at 13:29
  • As far as I know, detecting when a browser/tab *closes* is highly unreliable at best. Relying on it is generally considered a mistake in the originating use case. What if the user minimizes the browser instead? Or just opens another window in front of it? Or simply walks away? Or the OS fails? Or the computer loses power? Etc. Etc. You can't really rely on the *client* telling you when it plans to stop interacting. What you *can* do is keep a server-side timer based on the last interaction, occasionally ping the server from the page, maintain a web socket connection, etc. – David Aug 29 '23 at 13:32
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 30 '23 at 00:26

1 Answers1

2

When you close the browser your code is not running so can not do anything and you can not prevent users from closing the browser. The only thing you can do is show an alert in close that is handled by the browser. For security, the browser doesn't allow you to do sth like that.