Reputation: 1143
I know I can use onunload to do something when the user exits the page, the problem is that it works whether the user leaves the page, reloads, closes the page, etc.
I need to run a script only when the user leaves my page to another domain, ex:
if the user is in www.exemple.com/here and goes to www.exemple.com/there nothing should happen, but if he goes from www.exemple.com/here to www.anotherdomain.com/ then the script should run.
What´s the best way to do that?
As for why I need that, here is the story:
I work with googleTagManager and I need to fire a tag at the end of a session. The session only ends when the user closes the window or when he leaves the site domain. If he reloads or if the stays within the site, the tag should not fire.
Upvotes: 1
Views: 1706
Reputation: 6183
I needed something like this myself. I solved it by running a special function after the page loaded completely. This function attached a click event handler to all <a>
elements that checked where the link pointed to and set a flag depending on the link target. This flag was checked in my onunload
function so I could decide whether to show a warning or not.
But this was a very special implementation. This won't work for manual page changes (user enters URL) or javascript location changes.
Unfortunately I don't have the source code anymore, but it might look like this (using jQuery):
var leaving = false;
$(function() {
$('a').click(function() {
leaving = !$(this).attr('href').match(/regex/);
});
});
$(window).bind('beforeunload', function () {
return leaving ? 'Really want to leave the page?' : null;
});
(not tested!)
Edit: As Alex K. suggests in the comments, you may also hook forms, and not only links.
Upvotes: 3
Reputation: 73938
It seems not possible to get the next URL external to your domain, you can check for changes in the fragment identifier parameters ex; yourpage.html#sectiona
or yourpage.html#sectionb
using event onhashchange
on window
. Try the following script.
Please note this JS will work on modern browser IE8 >.
<!DOCTYPE html>
<html>
<head>
<script>
window.start = function(){
var url = "http://www.yoursite.com";
if ("onhashchange" in window) {
alert("The browser supports the hashchange event!");
}
function locationHashChanged() {
if (location.hash != url) {
alert('change url');
}
}
window.onhashchange = locationHashChanged;
}
</script>
</head>
<body onload="window.start();">
</body>
</html>
Upvotes: 0