Detect When User Navigates and Try to Close or Open a New Tab Using Javascript

I was working on a project where I need to show Call To Actions to the users whenever they try to navigate away from the document or when they want to close the current tab or open a new one.

addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;
    if (!from || from.nodeName == "HTML") {
        console.log('Are you sure you\'re gonna leave me?');

function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    } else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);

I already had this script working before in some other projects and it took me some time to find it again. So I am posting it here because sometimes memory gets stuck.

Add comment

E-mail is already registered on the site. Please use the Login form or enter another.

You entered an incorrect username or password

Sorry, you must be logged in to post a comment.