代码之家  ›  专栏  ›  技术社区  ›  ControlAltDel

从iframe中加载的html页面上的源脚本获取Javascript变量

  •  0
  • ControlAltDel  · 技术社区  · 3 年前

    以下是这个问题的后续内容: Accessing JavaScript variable in an iframe, from the parent window on same domain

    为了在这里发布一些可测试的东西,我有一个src。js文件设置如下:

    var foo = {"foo":"bar"};
    

    然后我可以创建一个HTML页面test1。头上有一行的html:

    <script src="src.js" type="text/javascript"></script>
    

    然后我有另一个HTML页面test2。html,带有

    <iframe src="test1.html"></iframe>
    

    如何从test2访问foo。html?我尝试了以下方法,但没有找到 foo (在test2.html中的一个div中单击按钮运行此功能)

      console.log("foo: " + typeof foo);
      console.log("foo: " + window.foo);
      console.log("Frame window: " + window.frames[0].window); //this works
      console.log("Sections: " + window.frames[0].window.foo);
    

    注意:在iframe中, 肯定有

    0 回复  |  直到 3 年前
        1
  •  1
  •   ControlAltDel    3 年前

    以下是最终对我有效的方法。在JS库中:

    const foo = {"foo":"bar"};
    
    window.getFoo = function() {
      return foo;
    }
    

    在带有iFrame(test2.html)的页面上:

      var iframe = document.getElementById("mainPanel"); //mainPanel is the id of the iframe
      var iWindow = iframe.contentWindow;
      var foo = iWindow.getFoo();