I need to create a javascript function that will find and replace all outbound links on my site. It will need to do the following:
Find all URLs that do not include 'mysite.com' in the url such as outbound links to anothersite.com
Replace the URLs with http://mysite.com/?redirect=anothersite.com
This sounds relatively straightforward... but I'm having issues.
Thanks in advance!
Here is an update with what I have so far to replace the URLs (which works):
<script type="text/javascript">
onload = function () {
for (var i = 0; i < document.links.length; i++) document.links[i].hre开发者_如何转开发f = 'http://www.mysite.com/redirect.php?' + document.links[i].href
}
</script>
I've tried a few different ways of just getting it to target the outbound URLs using an IF statement, but to no avail.
<script type="text/javascript">
onload = function () {
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].href.indexOf("http://www.mysite.com") == -1) {
document.links[i].href = 'http://www.mysite.com/redirect.php?' + document.links[i].href
}
}
}
</script>
Try something like this:
$('a').filter(function() { return this.hostname && this.hostname !== location.hostname; }).each(function(){
$(this).attr("href","http://www.mysite.com?redirect="+$(this).attr("href"));
});
JSFiddle
Not sure how much this will help but this is how to track outbound links for Google Analytics, I'm sure it should work for your purpose if you modify it accordingly:
<script type=”text/javascript”>
if (document.getElementsByTagName) {
var ahrefs = document.getElementsByTagName(‘a’);
for (var i=0; i<ahrefs.length;i++) {
if (ahrefs[i].href.indexOf(‘http://www.jhuskisson.com‘) == -1 && !ahrefs[i].onclick) {
ahrefs[i].onclick = function () { var track = this.href + ”; urchinTracker (‘/outgoing/’+track.substring(7)); }
}
}
}
</script>
Source: http://www.jhuskisson.com/...
var my_links = document.getElementsByTagName("a");
for (var i=0;i<my_links.length;i++){
if(my_links[i].href == <my site>){
my_links[i].href = location.replace(<whatever>);
}
}
work with this (should be fine, didn't try it, i'm not sure about that my_links[i].href = location... ) and put it inside a document.ready function!
You could do this with jQuery.
$('a').filter(function(){
if($(this).attr('href') != "http://www.mysite.com"){
$(this).attr('href', 'http://mysite.com/?redirect=' +
$(this).attr('href'));
}
});
http://jsfiddle.net/jasongennaro/XETqL/
精彩评论