Javascript problem with a global external link confirmation alert

Posted by OverDrive on Stack Overflow See other posts from Stack Overflow or by OverDrive
Published on 2009-06-27T15:57:59Z Indexed on 2010/03/16 15:31 UTC
Read the original article Hit count: 212

Filed under:
|
|
|
|

Below is the code from a plugin for Joomla. It works on it's own and it's purpose is to detect external links on the page and force them into new browser windows using _blank.

I've tried for about an hour (I don't know javascript well) but I can't seem to figure out how to get an onclick function working.

End result, I want to add to this script the ability of a confirmation dialog, shown in the 2nd code section.

An external link, when clicked, will pop up the confirmation dialog, and if it says yes, they will be able to get to the external URL, opening in a new window. Otherwise, it cancels, and does nothing.

When I create a link with

onclick="return ExitNotice(this.href);"
within it it works perfectly, but since my website has multiple people submitting input, I'd like the confirmation box global.

this.blankwin = function(){
  var hostname = window.location.hostname;
  hostname = hostname.replace("www.","").toLowerCase();
  var a = document.getElementsByTagName("a");   
  this.check = function(obj){
    var href = obj.href.toLowerCase();
    return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;  			
  };
  this.set = function(obj){
    obj.target = "_blank";
    obj.className = "blank";
  };    
  for (var i=0;i<a.length;i++){
    if(check(a[i])) set(a[i]);
  };    	
};

this.addEvent = function(obj,type,fn){
  if(obj.attachEvent){
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn](window.event );}
    obj.attachEvent('on'+type, obj[type+fn]);
  } else {
    obj.addEventListener(type,fn,false);
  };
};
addEvent(window,"load",blankwin);

Second Part

/* ----------
  OnClick External Link Notice
---------- */
function ExitNotice(link,site,ltext) {
  if(confirm("-----------------------------------------------------------------------\n\n" + 
    "You're leaving the HelpingTeens.org website. HelpingTeens.org\ndoes not " + 
    "control this site and its privacy policies may differ\nfrom our own. " + 
    "Thank you for using our site.\n\nYou will now access the following link:\n"  + 
    "\n" + link + "\n\nPress \'OK\' to proceed, or  press \'Cancel\' to remain here." + 
    "\n\n-----------------------------------------------------------------------")) 
  {
  return true;
} 
history.go(0);
return false;
}

A) Can anyone help me fix this problem? or B) Is there a better solution?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about link