View Full Version : Grab the URL of the clicked link on page unload
tflynn25
Oct 22nd 2008, 9:53 pm
Once a link is clicked, how can I grab the href attribute of it?
For my specific project, it must be done using the 'unload' event in jQuery.
<script type="text/javascript">
$(window).unload( function () {
alert( window.document.URL );
} );
</script>
window.document.URL and window.location.href both return the current domain. I want it to show the domain that is about to load.
lp1051
Oct 23rd 2008, 12:26 pm
Hi, I don't know exactly how with jQuery, but without, you probably need to attach event onclick to all links that can take you from the page. Something like
var a = document.getElementsByTagName("a");
var l = a.length;
for(var i=0; i<l; i++) {
a[i].onclick = function() { alert(a[i].href) }
}
Of course you have to filter the links, so you don't attach this on every link, just those that are pointing outside your current domain(window.location.href)
ToddMicheau
Oct 23rd 2008, 3:39 pm
How about this:
<html>
<body>
<SCRIPT>
var lastLink = "closedOut";
function setLastLink(theHref){
lastLink = theHref;
}
window.onbeforeunload = function(event){
if(lastLink != "closedOut"){
alert("Leaving to: " + lastLink + "! Bye!");
}
}
</SCRIPT>
<A HREF="http://www.bubblecoder.com/" onClick=setLastLink(this.href);>BubbleCoder!!!!</A>
</body>
</html>
Tested working in both FireFox v3.SomethingOrOther and what ever the latest crappy version of IE is. . .
(And yea, it's not jQuery, but you can change it. . . Dunno why your using jQuery anyway >.>)
salahsoftware
Oct 24th 2008, 1:42 am
The solution of Todd is working fine. I tested it in my system.
lp1051
Oct 25th 2008, 2:43 pm
Yeah, me too, even on older versions, great tip Todd. Where did you find this non-standard event?
ToddMicheau
Oct 25th 2008, 4:48 pm
You mean window.onbeforeunload()? That's standard. The rest is a simple function that just sets a variable to the href property of the clicked link.
I can also make you a JS function that will loop through every link on the page and set the onclick function- that way you don't have to do it manually. Just embed the JS.
lp1051
Oct 26th 2008, 3:27 am
Yes, I mean window.onbeforeunload(). I said non-standard, because I didn't find it in DOM 2 model or by W3c - JavaScript Event Reference. I know there's many events outside the scope of those documents, however I was just interested where did you come to this onbeforeunload.
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.