How do you change source location of iframes in JavaScript?
For example, but the click of a button or a link, change this:
<iframe src=""></iframe>
...into this:
<iframe src="http://stackoverflow.com/"></iframe>
And, if you want to do one better, how do I change multiple iframes within the same page (using name or some other identifier)?
-
This won't work, stack overflow uses frame busting and can't be framed (at least not easily) :-) .....adeneo– adeneo2012年12月14日 05:31:24 +00:00Commented Dec 14, 2012 at 5:31
4 Answers 4
First, assign you iframe an id. This would look like
<iframe id="youridname" src=""></iframe>;.
Then your JavaScript command would be
document.getElementById("youridname").src = "http://stackoverflow.com";
1 Comment
It's no different than modifying any other tag. Get the element, and set the property:
document.getElementsByTagName("iframe")[0].src = "http://stackoverflow.com";
And you can select against any attributes you like. For example, if you have <iframe data-id='some-frame' src='http://stackoverflow.com'></iframe>, then you could select against either attribute:
var soFrames = document.querySelectorAll("iframe[src*='overflow']");
if (soFrames.length > 0) {
soFrames[0].src = "something.com";
}
Or:
var soFrames = document.querySelectorAll("iframe[data-id='some-frame']")
(Note that there are security restrictions, so you can't just display any random website like Stackoverflow.com in your page's iframe.)
Comments
You can reference the frames in a page from window.frames. This contains a collection of the frames' window objects. From there you modify the location.href of the frame's window:
frames[0].location.href = "page1.htm";
frames[1].location.href = "page2.htm";
You can also get at a frame's window by referencing the frame element's contentWindow property:
document.getElementById("frame1").contentWindow.location.href = "page1.htm";
To go backwards, that is, get the frame element from it's window, use the frameElement property:
frames[0].frameElement;
Comments
document.getElementById("test").setAttribute("src", "http://stackoverflow.com");