DEV Community

loading...

Discussion on: Sure you want to leave?—browser beforeunload event

Collapse
samthor profile image
Sam Thorogood Author

Inside your beforeunload handler, you can add code in a setTimeout—probably even with a timeout of zero. That code will only run if the user allowed the page to stay open.

Collapse
oathkeeper profile image
Divyesh Parmar

Ok so we are basically making it async?

Thread Thread
samthor profile image
Sam Thorogood Author

Yeah, because your code otherwise won't have a chance to run.

I'd probably put a longer delay than zero on it, some browsers might let code execute even if the page is closing. I admit this behavior is a bit undefined.