简体   繁体   中英

How to call Javascript function from a iFrame?

I have 2 html files.

1.html will call 2.html from iframe.

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

2.html defined 2 javascript functions.

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

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

HTML

<body onload="func2()">

Now my question is, I have to merge these 2 html files to one html. 2.html must be executed inside the 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. Could anyone suggest the way to call javascript functions inside iframe?

Thanks in advance.

You can't call functions from iframe like that, due to CSP(Content Security Policy). The only way to comunicate outside of the iframe is with message passing. See this for explanation https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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