Javascript - Link Cloaking Script needs modifying

4.1k Views Asked by At

The following script adds my affiliate extension to every url on my page. For example, if http://www.Google.com/ is on my page somewhere... Adding this script to the page will automatically change the url to- http://adf.ly/xxxxxx/http://www.Google.com/ - this goes for every url on the page...

This script works great if the urls on the page are already hyperlinked, because the link text stays the same, but the destination url now has my affiliate extension on it.

My question is... How could I modify this script to make it so that raw urls (not hyperlinked) can still be shown as the original url, but with my affiliate extension added to the destination? Better put, I need this script to hyperlink all of the raw urls on the page. I need it so that if I have the raw url http://www.Google.com on my page, the script will change the destination to- http://adf.ly/xxxxxx/http://www.Google.com/ - but the viewer will still only see http://www.Google.com.

Again, this script works fine with hyperlinks already as it only affects the URLs, not the link text. I just need it to cloak/mask/hyperlink all of the raw urls, so that viewers still see the original URL destination, rather than the new one with my affiliate extension on it.

Thank you in advance, Here is the example HTML code:

<script type="text/javascript">
    onmousemove = function adfly() {
        adfly_id = 'xxxxxx';
        for(var i = 0; i < document.links.length; i++) {
            var hrefer = document.links[i].href;
            if(hrefer.match("adf.ly") || hrefer.match("javascript:") || hrefer.match("#")) {
                document.links[i].href = document.links[i].href;
            } else {
                document.links[i].href = 'http://adf.ly/' + adfly_id + '/' + document.links[i].href;
            }
        }
    }
</script>
2

There are 2 best solutions below

0
On

You could do it by:

  1. Going through text nodes (or the subset you are interested in), finding ones which contain a match for a URL regular expression.
  2. Create new nodes for:
    • the text parts
    • the anchor/links
  3. Insert these new nodes into the DOM (deleting/replacing the original text node)

This would be a loop separate to your existing one that goes through document.links.

Last but not least: be wary of XSS vulnurabilities!

1
On

The anchor tag below shows "google.fr" in the href attribute, but because of the onclick, clicking the link will take you to the site listed there instead.

 <a title="google" href="http://google.fr/whatpeopleseeonrollover" onclick="this.href='http://yahoo.fr/wherepeoplegoforreal'">http://google.fr/whatpeoplethinktheygo</a>

You could use something like this to redirect links on your page.