Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从iFrame调用Javascript函数?_Javascript_Html - Fatal编程技术网

如何从iFrame调用Javascript函数?

如何从iFrame调用Javascript函数?,javascript,html,Javascript,Html,我有2个html文件 1.html将从iframe调用2.html <iframe src="2.html" > </iframe> HTML 现在我的问题是,我必须把这两个html文件合并成一个html。2.html必须在iframe内执行 我试着通过 <!DOCTYPE html> <html> <body> <iframe id="foo" onload="myFunction()" /> <

我有2个html文件

1.html将从iframe调用2.html

<iframe src="2.html" > </iframe>
HTML


现在我的问题是,我必须把这两个html文件合并成一个html。2.html必须在iframe内执行

我试着通过

<!DOCTYPE html>
<html>

  <body>
    <iframe id="foo" onload="myFunction()" /> </iframe>
    <script>
      function myFunction() {
        var iframe = document.getElementById('foo'),
          iframedoc = iframe.contentDocument || iframe.contentWindow.document;
        iframedoc.body.innerHTML = func2();
      }

    </script>
  </body>

</html>

函数myFunction(){
var iframe=document.getElementById('foo'),
iframedoc=iframe.contentDocument | | iframe.contentWindow.document;
iframedoc.body.innerHTML=func2();
}
但是没有调用func2()。有人能建议在iframe中调用javascript函数的方法吗


提前感谢。

由于CSP(内容安全策略)的原因,您不能从iframe这样调用函数。在iframe之外进行通信的唯一方法是通过消息传递。请看下面的解释

<body onload="func2()">
<!DOCTYPE html>
<html>

  <body>
    <iframe id="foo" onload="myFunction()" /> </iframe>
    <script>
      function myFunction() {
        var iframe = document.getElementById('foo'),
          iframedoc = iframe.contentDocument || iframe.contentWindow.document;
        iframedoc.body.innerHTML = func2();
      }

    </script>
  </body>

</html>