Your best bet is listening on the non-standard beforeunload
event. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.
Kickoff example:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
This message will show up in kind of a confirmation dialogue.
In your specific case you need to turn it off (just set to null
) whenever a navigational link is clicked or an internal form is submitted. You can do that by listening on the click
event of the desired links and the submit
event of the desired forms. jQuery may be of great help here:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
You only need to give all external links the defacto standard attribute rel="ext"
to denote that those are external links.
<a href="http://google.com" rel="ext">Google</a>