I would like to detect when a user is about to exit the page, before they click the back button, and do something - for example display a popup. I do not want to prevent the user from leaving the page, but only to grab their attention again.
This is already done by Optin Monster, but I want to implement it myself.
Where to start?
Edit:
beforeunload
is fired after the user clicked the back or x button. I would like to catch his exit intent, for example when the mouse is moving towards the back button, but before it was clicked.
A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.
How to check if an opened browser window is closed or not in JavaScript? To check if an opened browser window is closed, you can use the closed property in referenced window object in JavaScript. The property returns a boolean true if the window is closed and false if the window is in the opened state.
Ouibounce does this. There is a live demo here.
npm install ouibounce
Then:
var ouibounce = require('ouibounce');
var modal = document.getElementById('ouibounce-modal')
ouibounce(modal);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With