Abhishek
Abhishek

Reputation: 4340

Change iframe source from another iframe

Ok, I have 2 iframes inside a parent page (for whatever reason).

I have a navigation menu on parent page, which changes the source of iframe #1...

iFrame #1's job, is to display ANOTHER navigation menu... Like a subnavigation menu...

Now, how can I upon clicking an li inside iFrame #1, change the source of iframe #2? They're both on the same parent page...

Aside from failing miserably, I also get a warning from Chrome's Dev tools -

Unsafe JavaScript attempt to access frame with URL file:///C:/website/index.html from frame with URL file:///C:/website/news/navigator.html. Domains, protocols and ports must match.

Here's some code to make things slightly clearer:

The HTML

<!-- HTML for the parent page itself -->
<iframe id="frameone" src=""></iframe>
<iframe id="frametwo" src=""></iframe>
<button onclick="onenav('test.html')">Change 1st frame</button>

<!-- The following is the HTML that is loaded inside "frameone" -->
<button onclick="twonav('test2.html')">Change 2nd frame</button>

// Javascript
var one = document.getElementById('frameone');
var two = document.getElementById('frametwo');

function onenav(x){
    one.src = x;
}

function twonav(y){
    two.src = y;
}

To me, this makes sense, since this is all being executed on the parent page... On loading, I query the dev tools and I can see that both, 'one' and 'two' have frame elements... The first button works, the second one, doesn't...

Upvotes: 3

Views: 12456

Answers (2)

mplungjan
mplungjan

Reputation: 177786

Works for me when using parent.twonav

DEMO

var links = [
    'javascript:\'<button onclick="parent.twonav(1)">Change 2nd frame</button>\'',
    'javascript:\'Hello\''
];
var one, two;
window.onload=function() {
  one = document.getElementById('frameone');
  two = document.getElementById('frametwo');
}  

function onenav(idx) {
    one.src=links[idx];
}  

function twonav(idx) {
    two.src=links[idx];
}  

Upvotes: 5

Ziga Petek
Ziga Petek

Reputation: 4110

How did you try to change the iframe source?

parent.document.getElementById('2').src = "the new url";

Did you try something like this? I assumed from your message that the id of the 2nd iframe is 2.

Upvotes: 0

Related Questions