How to execute a function and track outbound link on page exit using Javascript?
-
02-07-2021 - |
Pergunta
I want to execute few functions before the page just exits such as logging page exit time.
The onbeforeunload
event when used shows a pop-up which I don't want.
Somehow when an outbound link is clicked, it should enter a function, fetch the link href
, execute and then exit the page.
Without using JQuery
.
Is this possible?
Solução
links = document.getElementsByTagName('a')
for(var i=0; i<links.length; i++){
links[i].addEventListener('click', function(event){
//do your stuff
return true;
});
};
give that a shot.
If you need information about the link itself, use the this
construct. Specifically:
this.href
will get you the link address.
Outras dicas
onbeforeunload
only alerts when a return value is specified.
Try using this to detect when an outbound link is clicked:
var a = document.getElementsByTagName('a'),
i = a.length,
domain = new RegExp(location.href.match(/(^.*)\./)[1]),
onLeave = function () {
if (!domain.test(this.href)) {
alert('Leaving!');
}
};
while (i--) {
a[i].onclick = onLeave;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow