[英]javascript page element access from one child iframe to another child
I´m trying to access a few elements from a child iframe to another... 我试图从儿童iframe访问另一个元素到另一个...
I´ve tried to reference childNodes with no luck (alert 0): 我试图在没有运气的情况下引用childNodes(警报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.
提前致谢。
This is your parent element: 这是您的父元素:
<iframe src="iframe1.html"></iframe>
<iframe src="iframe2.html"></iframe>
And this is your input in iframe1.html: 这是你在iframe1.html中的输入:
<input id="inp" value="HELLO!!!">
Let's retrieve it's value in iframe2.html: 让我们在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 data to >>> iframe2
Iframe1: (sends) Iframe1 :(发送)
<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) Iframe2 :(收到)
<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. 您应该在iframe2中看到
p
元素增加从iframe1发送的数字。
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.