Reputation: 49
I´m trying to access a few elements from a child iframe to another...
I´ve tried to reference childNodes with no luck (alert 0):
alert(window.parent.document.getElementById('framechildidonparent').childNodes.length);
Also tried to go upward to parent and then down to child with no luck:
function getParentFrameProperties(idframe,idobject){
var myframe = window.parent.document.getElementById(idframe).contentWindow;
var insideobject = myframe.document.getElementById(idobject).value;
alert(insideobject);
}
Any clues? Thanks in advance.
Upvotes: 4
Views: 642
Reputation: 206121
This is your parent element:
<iframe src="iframe1.html"></iframe>
<iframe src="iframe2.html"></iframe>
And this is your input in iframe1.html:
<input id="inp" value="HELLO!!!">
Let's retrieve it's value in iframe2.html:
parent.window.onload = function(){
var ifr1 = parent.document.getElementById("ifr1");
var ifr1_DOC = ifr1.contentDocument || ifr1.contentWindow.document;
console.log( ifr1_DOC.getElementById("inp").value ); // "HELLO!!!"
}
Pseudo:
iframe1 >>> postMessage to window.parent
iframe2 >>> addEventListener to window.parent that will listen for postMessage events
This is your parent element:
<iframe src="iframe1.html"></iframe>
<iframe src="iframe2.html"></iframe>
Example: iframe1 >>> sends data to >>> iframe2
Iframe1: (sends)
<script>
var n = 0;
function postToParent(){
el.innerHTML = n;
// IMPORTANT: never use "*" but yourdomain.com address.
parent.postMessage(n++, "*");
}
setInterval(postToParent, 1000);
</script>
Iframe2: (receives)
<p id="el">NUMBER CHANGES HERE</p>
<script>
var el = document.getElementById("el");
function receiveMessage(event) {
// Do we trust the sender of this message?
// IMPORTANT! Uncomment the line below and set yourdomain.com address.
// if (event.origin !== "yourdomain.com") return;
el.innerHTML = event.data;
}
parent.addEventListener("message", receiveMessage, false);
</script>
You should see in iframe2 the p
element increase numbers that are sent from iframe1.
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Upvotes: 2