javascript页面元素从一个子iframe访问另一个子项

时间:2015-03-05 22:58:12

标签: javascript iframe

我正在尝试从子iframe访问一些元素到另一个...

我试图引用没有运气的childNodes(警报0):

alert(window.parent.document.getElementById('framechildidonparent').childNodes.length);

还试图向上走向父母,然后向下生孩子,没有运气:

function getParentFrameProperties(idframe,idobject){
  var myframe = window.parent.document.getElementById(idframe).contentWindow;
  var insideobject = myframe.document.getElementById(idobject).value;
  alert(insideobject);
}

任何线索?提前谢谢。

1 个答案:

答案 0 :(得分:2)

从其他iframe中检索元素值:

这是您的父元素:

<iframe src="iframe1.html"></iframe>
<iframe src="iframe2.html"></iframe>

这是你在iframe1.html中的输入:

<input id="inp" value="HELLO!!!">

让我们在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!!!"

}

在iframe之间进行实时通信:

伪:

iframe1 >>> postMessage to window.parent
iframe2 >>> addEventListener to window.parent that will listen for postMessage events

这是元素:

<iframe src="iframe1.html"></iframe>
<iframe src="iframe2.html"></iframe>

示例:iframe1 >>> sends data to >>> iframe2

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 :(收到)

<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>

您应该在iframe2中看到p元素增加了从iframe1发送的数字。

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage