How can I detect a user about the exit the page?

Tzach picture Tzach · Jun 3, 2014 · Viewed 18.7k times · Source

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.

Answer

A. Wolff picture A. Wolff · Jun 3, 2014

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);