0

I have an iframe that I run code inside. I don't know the iframes ID as it's set by another application. I wish to change the page in the iframe to another url. How can I do this without knowing the id?

sample html: http://plnkr.co/edit/kE9WdSTWe4GdDKPbFboV?p=catalogue

asked Apr 30, 2014 at 16:11
4
  • document.getElementsByTagName('iframe') should do Commented Apr 30, 2014 at 16:12
  • 1
    the method commented by phylax is only aplicable if you have a single iframe only, can you put your code in jsfiddle? Commented Apr 30, 2014 at 16:13
  • what code? I', running a facebook-tab-app, I could select the iframe in some various ways, but it's hard to be sure it won't change, thus breaking the app. Commented Apr 30, 2014 at 16:16
  • @KristofferNolgren It would be good to share your rendered HTML, can you share ? Commented Apr 30, 2014 at 16:20

2 Answers 2

2

If you know the URL that you want to replace you can do this :

var frames = document.getElementsByTagName("iframe");
for (var i = frames.length - 1; i >= 0; i--)
{
 if(frames[i].src == "currentURL"){
 frames[i].src = "newURL"
 }
}

Or If you are the page inside the iframe you can simply redirect the page :

window.location.replace("http://www.newlocation.com")
answered Apr 30, 2014 at 16:22
Sign up to request clarification or add additional context in comments.

10 Comments

But when I think about it, will this really work to run inside the iframe, does my iframe know what's outside it, including itself?
@KristofferNolgren what exactly is the context of the script? are you trying to put this script in a page that will be called by an iframe and then you want to change the source of the iframe? or will this be in your page that contains the iframe?
the first, inside a page that will be called by an iframe.
@KristofferNolgren let me know if this works, but I don't think it will. I'm going to look into it, but I think it can be done.
@KristofferNolgren you don't even need to do that actually... here is what you can do : window.location.replace("http://www.newlocation.com")
|
2

If you have a single iframe, do this:

document.getElementsByTagName('iframe')[0].src = "url"

getElementsByTagName returns NodeList, on which you can use index to use the specific element from the list.

Index start at 0

answered Apr 30, 2014 at 16:13

1 Comment

Nice, i don't though, I have facebook-buttons and vime-windows aswell.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.