gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:31 25 4
gpt4 key购买 nike

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

我曾尝试引用子节点,但没有成功(警报 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);
}

有什么线索吗?提前致谢。

最佳答案

从其他 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 >>> 发送数据到>>> 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

关于从一个子 iframe 到另一个子的 javascript 页面元素访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28889461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com