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.

Cromwell Bayon

He is a self-tutored programmer and a Full-Stack Developer. He strives to excel in the newest technology as possible. He has a very high sense of technicality and analytical skills which allows him to resolve any kind of issues related to technology. He also loves woodworking. Read more about him here...

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.