OnUnload message needed for external links

tumtummetjes picture tumtummetjes · May 27, 2010 · Viewed 10.7k times · Source

I need a message script that will only come up when people are leaving the current webpage and not the current website.

When people are leaving the website entirely, the message will come up and they will need to press the OK button to stay at the current page (and cancel to leave the website).

The script may not run when people actually stay on the website or when they click on internal links or pages.

Can this be done?

Answer

Adam picture Adam · May 28, 2010

Check out this very basic example solution. It sets the onbeforeunload handler but then removes it if the user clicks an internal link. Below is a generic version of the code from the example solution.

HTML:

<a href="internal_link.html">internal link</a>
<a href="http://www.example.com">external link</a>

JS (uses jQuery):

window.onbeforeunload = function(){
    return "Are you sure you want to leave our website?";
}
$(function(){
    $('a, input, button').click(function(){
            window.onbeforeunload = null;
    });
});