Hi all,

I am trying to edit this script so that it not only changes offsite targets to _blank, but also changes their href from their original link, to http://www.mydomain.com/externallinks/+origionallink

Can somebody help me find out what is wrong with this script? It is editing the target and href of onsite links as well, even though before i made my changes it was working as i want it.

This section of the code is intact:

//Open offsite links in new window script- http://www.dynamicdrive.com/
//Created: August 28th, 2007'

var ddwindowlinks={
//1)Enter domains to be EXCLUDED from opening in new window:
excludedomains: ["mydomain.com"],

//2) Target for links that should open in a new window (ie: "_blank", "secwin" etc):
linktarget: "_blank",

//3) Specify operating mode ("auto" or "manual"):
mode: "auto",

//4) If mode is "manual", customize checkbox HTML to show to users (Preserve id attribute):
toggleHTML: '<form><input type="checkbox" id="targetcheckbox" checked="checked" /><label for="targetcheckbox">Open off-site links in new window?</label></form>',

//5) If mode is "manual", enable user persistence so the state of the checkbox is remembered?
persist: true,

This part of the code has been edited:

assigntarget:function(){
	var idinc = 1
	var rexcludedomains=new RegExp(this.excludedomains.join("|"), "i")
	var all_links=document.getElementsByTagName("a")
	if (this.mode=="auto" || (this.mode=="manual" && this.togglebox.checked)){
		for (var i=0; i<=(all_links.length-1); i++){
			if (all_links[i].hostname.search(rexcludedomains)==-1 && all_links[i].href.indexOf("http:")!=-1)
				all_links[i].target=ddwindowlinks.linktarget
				var idinc = idinc+1
				all_links[i].id = idinc;
				var activehref = document.getElementById(idinc); // from above code.
all_links[i].href=''+activehref;

This part of the code is intact:

}
	}
	else{
		for (var i=0; i<=(all_links.length-1); i++)
			all_links[i].target=""
	}
	if (this.mode=="manual" && this.persist)
		this.setCookie("dlinktarget", (this.togglebox.checked)? "yes" : "no", 30) //remember user setting for 30 days (set to -1 then reload page to erase cookie)
},

init:function(){
	if (document.getElementById && this.mode=="manual"){
		document.write(this.toggleHTML)
		this.togglebox=document.getElementById("targetcheckbox")
		this.togglebox.onclick=function(){ddwindowlinks.assigntarget()}
		if (this.persist && this.getCookie("dlinktarget")!="")
			this.togglebox.checked=(this.getCookie("dlinktarget")=="yes")? true : false
	}
	if (window.addEventListener)
		window.addEventListener("load", function(){ddwindowlinks.assigntarget()}, false)
	else if (window.attachEvent)
		window.attachEvent("onload", function(){ddwindowlinks.assigntarget()})
},

getCookie:function(Name){
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
},

setCookie:function(name, value, days){
	var expireDate = new Date()
	//set "expstring" to either an explicit date (past or future)
		var expstring=expireDate.setDate(expireDate.getDate()+parseInt(days))
		document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"
}

}

ddwindowlinks.init()

Thanks all,

Max Mumford.

Dani AI

Generated

Quick diagnosis and a safe fix

The symptom you reported (onsite links also being rewritten) usually comes from two mistakes: missing braces so only the first statement after your if is actually conditional, and then trying to build the new URL by calling getElementById on a numeric id instead of using the link object you already have. The first makes the rewrite run for every anchor; the second yields an object instead of the original href. As suggested, marking external anchors manually is a simple, robust option. If you want automatic detection, operate on the loop variable (the link node), check protocol/hostname, and always encode the original URL when you append it as a query string.

Example pattern (safe, avoids numeric IDs and preserves encoding)

document.addEventListener('DOMContentLoaded', function () {
  var links = document.querySelectorAll('a[href^="http"], a[href^="//"]');
  for (var i = 0; i < links.length; i++) {
    var a = links[i];
    if (a.hostname === location.hostname) continue;               // skip same-site links
    if (!/^https?:$/i.test(a.protocol)) continue;                 // skip mailto:, javascript:, etc.
    a.setAttribute('target', '_blank');
    a.setAttribute('rel', (a.getAttribute('rel') || '') + ' noopener noreferrer');
    a.href = 'https://example.com/externallinks/?url=' + encodeURIComponent(a.href);
  }
});

Troubleshooting checklist

  • Add braces around multi-line if blocks so all intended statements are conditional.
  • Log a.href and a.getAttribute('href') to see absolute vs. original values.
  • Use encodeURIComponent when embedding a URL as a query value.
  • Avoid assigning numeric-only IDs to anchors; you already have a direct reference to the element.
  • Prefer rel="noopener noreferrer" with _blank for security.

That combination fixes the bug you saw and avoids the common pitfalls that produced the behavior reported.

Recommended Answers

All 2 Replies

Member Avatar for Member #380484

For your edited code (if it were me) I would do something like this

var all_links = document.getElementsByTagName("a");
for ( var i = 0; i < all_links.length; i ++ ) {
  if ( all_links.item(i).rel == 'resource' ) {
    var link = all_links.item(i);
    link.href = ''+ link.href;
    link.target = 'blank';
  }
}

And for any links that reference an external site I would do this

<a href="http://www.somesite.com" rel="resource">Some Site</a>

That is use the "rel" attribute to signify that it is an external link ... of course you can use RegEx to grab the "http://" of the link and that is good and all, but RegEx tends to be pickier than the human mind and often finds scenarios to break in that we never anticipated -- so I avoid it where it makes sense to use an alternative -- following the KISS principle.

Good luck

That worked fine, thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.