简体   繁体   English

如何从iFrame调用Javascript函数?

[英]How to call Javascript function from a iFrame?

I have 2 html files. 我有2个html文件。

1.html will call 2.html from iframe. 1.html将从iframe调用2.html。

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

2.html defined 2 javascript functions. 2.html定义了2个javascript函数。

function func1(a, b, c) {
  for () {
    .....
  }
}

function func2() {
 func1(a, b, c);
}

HTML HTML

<body onload="func2()">

Now my question is, I have to merge these 2 html files to one html. 现在我的问题是,我必须将这2个html文件合并为一个html。 2.html must be executed inside the iframe. 2.html必须在iframe中执行。

I tried to do by, 我试图做到

<!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>

But func2() is not called. 但是不调用func2()。 Could anyone suggest the way to call javascript functions inside iframe? 有人可以建议在iframe中调用javascript函数的方法吗?

Thanks in advance. 提前致谢。

You can't call functions from iframe like that, due to CSP(Content Security Policy). 由于CSP(内容安全策略),您无法从iframe调用此类函数。 The only way to comunicate outside of the iframe is with message passing. 在iframe之外进行通讯的唯一方法是传递消息。 See this for explanation https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage . 请参阅此以获得解释https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM