Skip to content Skip to sidebar Skip to footer

How To Check I Am Leaving To Another Website Using Jquery?

I want to show alert when user is leaving our website within same tab of the browser. I searched and found unload event, which triggers each time both when user is leaving or click

Solution 1:

I see your question now, answer is NO, you can not do it, you can do whatever on your page in your domain, you have full control of it, but you can't not detect you are going to a different domain, just not possible, that the browser's behavior, and if the other site does not have your script, you have lost control on the browser.

For example, any time if the browser loads your script, you have all control, once it went to a different site, browser unload your script, what you can do? But sure, if you have scripts loaded, you can always check what is your current path/domain.

Solution 2:

You can indeed use the unload event. The thing missing is navigating away when a user clicks on your own links.

This can be achieved by adding a click handler on all your links which sets a global flag (e.g. userClicked=true) which can be used in the unload handler

Example (jsFiddle):

var userClicked = false;
$( "body" ).delegate( "a", "click", function() {
    userClicked = true;
});

window.onbeforeunload = function() {
    if (!userClicked) {
        return"Your message";
    }
}

Post a Comment for "How To Check I Am Leaving To Another Website Using Jquery?"