28 April 2010

Javascript: Set or get URL/URI/src/href of an iframe or frame/frameset function

This function simply targets an iframe or frameset and retrieves or changes it's src or href attribute.

Tested in FF 3.6 and Chrome (might need some tweaking for IE)

The Function: (Please see right hand pane before copying my code - thank you! >>>)

/*loads a url in the specified frame/iframe or returns the loaded url if url arg is blank
frame  //DOM reference to a frame/iframe or string ID of an iframe in this document
url  //url to href to. ignore or set=0 to return current url of page
*/
function framehref(frame,url){
 if(typeof(frame)=='string'){//find iframe (will not find a frame):
  frame=document.getElementById(frame);
 }
 if(frame.tagName=='IFRAME'){//iframe:
  if(url==undefined){ return( frame.contentWindow.document.location );}
  frame.contentWindow.document.location.href=url;
 }else{//frame:
  if(url==undefined){ return( frame.document.location );}
  frame.document.location.href=url;
 }
}

//sample usage:
alert(framehref('myIframe')); //alerts the current location of the iframe 
framehref('myIframe',"http://www.google.com/"); //sends the iframe to google homepage
framehref(top.right,"http://www.google.com/"); //sends the right hand frame (in a frameset) to google homepage

3 comments:

Anonymous said...

frame.contentWindow.document.location.href=url;

This wouldn't work if the iframe contents aren't within the same domain with the parent page...

cron said...

Correct: all cross-domain actions in javascript are blocked by the browser for security reasons.

Meiqing Xu said...

jordan shoes
canada goose jackets uk
hermes handbags
kobe shoes
michael kors uk
ralph lauren
buy red bottoms
louis vuitton handbags outlet
rolex replica watches
christian louboutin outlet
20161228caiyan

Post a Comment

Cron Design Studio: Dublin based web design & software development