Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how do I determine if a link targets the same domain as the page it resides on?

For the purposes of tracking non-HTML documents via google analytics, I need the mentioned algorithm. It should:

  • not hard-code the domain
  • ignore the protocol (i.e. http/https)
  • not worry about the presence/absence of "www" (any absolute links WILL prefix with "www" and all pages WILL be served via "www")

This is complicated by the fact that I need to access it via a function called from the IE-only 'attachEvent'.

UPDATE Sorry, I've worded this question really badly. The real problem is getting this to work via an event, since IE has its own made-up world of event handling. Take the following:

function add_event(obj) {
    if (obj.addEventListener)
        obj.addEventListener('click', track_file, true);
    else if (obj.attachEvent)
        obj.attachEvent("on" + 'click', track_file);
}

function track_file(obj) { }

It seems as if the "obj" in track_file is not the same across browsers - how can I refer to what was clicked in IE?

like image 366
Bobby Jack Avatar asked Nov 25 '08 11:11

Bobby Jack


Video Answer


2 Answers

I would like to point out that, if you're on so.com, the following links are URLs within the same domain:

  • http://test.so.com
  • http://so.com/index
  • index
  • /index
  • #
  • /#
  • https://subdomain.so.com#hash
  • mail.google.com
  • mail.google.com/index.php?var=value#index

(it may seem odd, but the last two ones are valid: if you're on http://so.com, the last one would take you to http://so.com/mail.google.com/index.php?var=value, which is perfectly valid)

This doesn't really answer the question but I hope it will guide the rest of the answers. If there's anything else weird enough, feel free to add it.

like image 184
2 revs Avatar answered Sep 21 '22 12:09

2 revs


This sounds like a comedy answer but in all seriousness it would be be advisable that you could also do something like:

$('a.external')

Certainly the regex comparison to your window.location is the programmatic answer.

like image 38
annakata Avatar answered Sep 21 '22 12:09

annakata