Ad

How Do I Prompt A Modal When The User Leaves My Website In Javascript/AngularJS?

Is there a way in AngularJS or Javascript to detect that the user is leaving my website (can be closing his browser or entering another page) and to prompt a modal? In this modal I want to ask the user why he is leaving.

Also, is it OK to have something like this? Will my website be blacklisted due to this "annoying: feature?

Ad

Answer

To combat unwanted pop-ups, modern browsers severely limit what JavaScript can do before a page unloads.

From the Docs:

Window: beforeunload event

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. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.

For more information, see

Ad
source: stackoverflow.com
Ad