【问题标题】:access value of variable from iframe at the parent level在父级从 iframe 访问变量的值
【发布时间】: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


【解决方案1】:

contentWindow 是本机窗口的属性;您正在尝试在 jQuery 对象上调用它。

改变

$("#one-time-form").contentWindow.useableData;

$("#one-time-form")[0].contentWindow.useableData;

【讨论】:

  • 这是清除控制台日志,所以我们正在取得一些进展!但是返回的值说它是未定义的
【解决方案2】:

您在主窗口加载后运行此程序,您需要等待 iframe 加载完毕。

正如另一个答案中提到的,contentWindow 是一个 DOM 属性,而不是 jQuery 属性,因此您需要直接访问 iframe DOM 元素。

$(document).ready(function() {
    $("#one-time-form").on("load", function() {
        var fName = document.getElementById("one-time-form").contentWindow.useableData;
        console.log(fName);
    });
});

【讨论】:

  • 利用这种方法并访问正确的 contentWindow 如另一个答案中所述正在清除控制台错误,但仍返回未定义的变量。这个答案是否旨在解决函数的加载方式? iframe 完成加载后,我似乎仍然没有运行此功能
  • 正如我在上面的评论中提到的,您可能需要使用消息接口等待 iframe 中的 JS 完成。
  • 谢谢@Barmar - 您是否有足够的消息界面经验,可以帮助我制作一个示例供我尝试?
  • usableData 在 iframe 中是如何分配的?是同步完成还是异步完成?
  • 如果您尝试,如果不起作用,我可以提供帮助。
猜你喜欢
  • 2012-11-25
  • 2012-05-24
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 2016-01-25
  • 2015-09-24
  • 1970-01-01
相关资源
最近更新 更多