Click here to Skip to main content
15,798,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

i have an iframe displaying a web page.
is it possible to change the iframe src when a button on the page displayed in the iframe is clicked?


Yes, you can. The key here is to just treat the Iframe like it's a browser window/tab in it's own right.

Consider the following excerpt of html - code that is displayed inside the iframe.

function changeSrc()
    var oiFrame = document.getElementById('mIframe');
    oiFrame.src = 'index.php';

function changeSrc2()
    window.location = 'index.php';

    Contents of Iframe
    <button onclick='changeSrc2();'>Change iFrame src</button>


Now, consider the following excerpt - code that contains the iframe
<iframe id='mIframe' src='iFrameSrc.html'/>

The first function, changeSrc will do nothing there - the first line of code returns null. You obviously can't set the src attribute of null.

The second function will change the src attribute of the iframe found in whatever.html. You'll notice that if you just type iframeSrc.html into the browsers address-bar, you'll get the page in the whole window. Clicking the button will change the displayed address _and_ displayed content. The point is, the code for changing the url is the same, whether the page is displayed as is or if the page is shown inside an iframe.

However, we can still make the changeSrc function work. But we have to remove it from iFrameSrc.html and paste it into whatever.html.

You can change the src of an iframe - both from within the iframe and from outside of it. You just have to go about it differently in each case. changeSrc will do so from outside. changeSrc2 will do it from inside.
Share this answer
Sure. Just use JavaScript like this:

var oiFrame = document.getElementById(iFrame);
oiFrame.src = someurl;
Share this answer
enhzflep 22-Nov-13 17:21pm    
Er, are you sure about this? It looks like you may have misread the question.

This code will work fine if it's called from the page that contains the iframe
But, not if it's called from the page displayed in the iframe
ZurdoDev 22-Nov-13 20:51pm    
Oops. You're right. Then they can do window.location = newUrl;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900