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

9 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...

Unknown said...

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

Unknown 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

chenlili said...

coach outlet
michael kors outlet
nfl jerseys wholesale
christian louboutin outlet
coach outlet online
canada goose outlet
canada goose outlet store
canada goose outlet
christian louboutin sale
pandora outlet
shenyuhang20180608

Unknown said...

20180623xiaoke
polo ralph lauren outlet
air max 2018
cheap jordans
canada goose jackets
coach outlet store online
dsquared2 jeans
cheap jordan shoes
oakley sunglasses wholesale
michael kors outlet clearance
coach outlet store online

chenlili said...

ugg outlet
nike outlet
michael kors
jordan shoes
air jordan
lee jeans
nfl jerseys
cheap nfl jerseys
nike free
jordan 12
201811.9chenjinyan

Unknown said...

안동출장샵
안동출장샵
전주출장샵
무주출장샵
전주출장샵
영주출장샵
군산출장샵

Unknown said...


광양출장샵
광양출장샵
상주출장샵
진안출장샵
상주출장샵
전북출장샵
전북출장샵


Unknown said...

제주도출장안마
제주도출장안마
인제출장안마
서귀포출장안마
제주출장안마
고성출장안마
제주출장안마
제주출장안마

Post a Comment

Cron Design Studio: Dublin based web design & software development