views:

117

answers:

3

Here is my problem. I'm working within a CMS and users are able to create hyperlinks (both internal and external) I'm wondering if there is a good way to check when a user clicks a link if they are navigating to an external site. I don't want to do anything if they use the back/forward buttons, type something into the address bar, etc. I just want to redirect them to a page within our site that takes the address they REALLY want to go to in he query string and display a 5 second (or so) message telling them they are leaving our site and we aren't responsible for what is there etc etc. Since end users will be responsible for generating most of the links, teaching them to actually point links at the intermediate page is less than ideal so I was wondering if there is an easy solution using javascript.

A: 

You should replace users' links with your own special links (e.g. http://yoursite.com/redirect.ashx?http://external.com) when they save their data or, the better way, when you are serving user-generated contents to other users.

Li0liQ
Getting at the code where they generate these links is not an option. We're using a third party tool and cannot modify it. What I'm really looking for is a way to catch when an external hyperlink is clicked and handle it there.
Ben
+1  A: 

You could use jQuery to attach a click event for all links on your site that are external (start with http, minus some special cases), which could then either show a modal dialog, or set window.location to your intermediate page (you can tack on a query string var for the external url). You can make a custom selector to get external links, then attach the behavior:

$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname);
};

$('a:external').click(function() { 
    //show your dialog box or set window.location
    //link in question will be $(this).attr('href')
});
wsanville
A: 

I think I am going to something similar to wsanville's answer. Except what I will be adding a click event to all anchor tags and then checking if their href value is within our domain.

So something like:

$('a').click(function() {
    if this.href.indexOf('mydomain.com'!=-1)
      return true;
    else{
      window.location = "intermediate.html?href=" + this.href;
    }
});

Anyone know what kind of performance hit attaching an event to every anchor tag on a page could have?

Ben