【问题标题】:Pass a Javascript Object to an HTML iframe (as an Object)将 Javascript 对象传递给 HTML iframe(作为对象)
【发布时间】:2016-07-03 12:40:30
【问题描述】:

MainWindow 创建一个 JavaScript 对象,ChildWindow 需要利用该对象。

我的 MainWindow.html 现在看起来像这样

<html>
  <body>
    <script>
      var varObject = {type:"Error", message:"Lots"};
    </script>
    <iframe class="child" src="ChildWindow.html"></iframe>
  </body>
</html>

ChildWindow.html 看起来像这样

<html>
  <body>
    <script>
      console.log(varObject.type); // goal is to log "Error"
    </script>
  </body>
</html>

ChildWindow 正在尝试使用在 MainWindow 中创建的对象,但它当然不能,因为我还不知道如何传递它。

我尝试在 Google 上搜索这个,但我发现的大多数解决方案都涉及将值作为字符串而不是变量传递。

【问题讨论】:

    标签: javascript html iframe scope arguments


    【解决方案1】:

    可以通过将对象分配给 iframe 的 window 来简单地传递对象。

    在父窗口中:

    var frame = document.querySelector("iframe");
    frame.contentWindow.object_of_interest = object_of_interest;
    

    在 iframe 窗口中

    console.log(window.object_of_interest);
    

    【讨论】:

    • 必须是 contentWindow 而不是 contextWindow?
    • 正如@abdolence 建议的那样,使用 contentWindow 为我工作。
    • SecurityError: 访问跨域对象上的属性“object_of_interest”的权限被拒绝
    • @Oram - iframe 中的“网站”必须允许跨域访问(或具有相同来源)才能修改其数据。如果浏览器允许用户无限制地打开其他网站并修改这些网站中的数据,则可能存在许多安全风险。
    • 我添加了评论,因为您不能“简单地传递对象”。正如您在回复中提到的那样,您有限制。
    【解决方案2】:

    您应该使用window.postMessage 与嵌入在您网站中的 iFrame 之间发送消息。

    【讨论】:

    • 不一定是消息,有时是数据库连接对象
    • 您可以使用JSON.stringify(obj) 将您的对象转换为字符串,并使用JSON.parse(str) 将它们再次转换回来。
    • 如果对象是 Promise 或函数或任何其他更复杂的对象结构,这将不起作用。
    【解决方案3】:

    请看下面的代码:

    <html>
      <body>
        <script>
          var varObject = {type:"Error", message:"Lots"};
          var child = document.getElementsByClassName("child")[0];
          var childWindow = child.contentWindow;
          childWindow.postMessage(JSON.stringify(varObject),*);
        </script>
        <iframe class="child" src="ChildWindow.html"></iframe>
      </body>
    </html>
    

    在 ChildWindow.html 中

    <html>
      <body>
        <script>
          function getData(e){
            let data = JSON.parse(e.data);
            console.log(data);
          }
          if(window.addEventListener){
            window.addEventListener("message", getData, false);
          } else {
            window.attachEvent("onmessage", getData);
          }
        </script>
      </body>
    </html>
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 2011-12-07
      • 2017-07-21
      相关资源
      最近更新 更多