【发布时间】:2021-05-07 23:35:45
【问题描述】:
我已经阅读了无数类似问题的答案,但我没有得到我需要的结果。
对于背景...我在我的页面中嵌入了一个 iframe。父级和 iframe 都在同一个域上。我想在父页面中访问 iframe 中的一些变量。
为iframe服务的父页面的html是这样的;
HTML
<iframe id="one-time-form" width="100%" height="1850px" src="https://www.domain-that-parent-and-iframe-reside-on.com/page-url-for-iframe"></iframe>
在 iframe src 中是一个存储数据数组的变量。这个变量叫做var useableData
我知道我的 iframe 加载晚于父页面,所以我尝试调用这个存放在 jQuery 函数中的变量,该函数在整个窗口完成加载后运行。
jQuery
$(window).load(function () {
var fName = $("#one-time-form").contentWindow.useableData;
console.log(fName);
});
这只是返回一个控制台错误 Uncaught TypeError: Cannot read property 'useableData' of undefined
关于为什么这不起作用或对我应该采取的方法进行修改的任何想法?
更新
已尝试实现postMessage(),但它也不合作。我基于这个演示:https://usefulangle.com/post/4/javascript-communication-parent-child-window
在子页面中我运行了这个:
子消息
//Function to send data back to the parent window
function ProcessChildMessage(message) {
var testMessage = useableData;
}
然后在父页面我调用这个函数
家长留言
window.opener.ProcessChildMessage('Message to the parent');
仍然没有任何运气,我看到这个控制台错误“Uncaught TypeError: Cannot read property 'ProcessChildMessage' of null”
【问题讨论】:
-
load事件在 DOM 加载时发生,但脚本可能尚未运行。您可能应该使用postMessage()机制在 iframe 和父级之间进行通信。 -
顺便说一句,
load事件处理函数的函数形式已弃用,您应该使用.on("load", function...) -
$("#one-time-form")返回一个 jQuery,而不是原生元素。你可以试试$("#one-time-form")[0].contentWindow或$('#one-time-form').get(0).contentWindow
标签: javascript jquery iframe