Access iframe functions

2019-07-11 12:37发布

问题:

This problem seem to happen only in chrome This is the iframe code

<!DOCTYPE html>
<html>
<head>
    <script>
    function blahblah() { alert("test"); }
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Test Page</title>
</head>
<body>

    <p> lalalalallalala!!! </p>

</body>
</html>

This is how I create the iframe

<iframe src="iframetest.html" id="iframetest"></iframe>

I then try to call the iframe's blahblah() function:

$('#iframetest')[0].contentWindow.blahblah()

But this doesn't work

回答1:

This works :

  <iframe id=iframetest src=iframetest.html></iframe>
  <script>
      $(window).load(function(){
         document.getElementById('iframetest').contentWindow.blahblah();
      });
  </script>

Note that I used $(window).load to ensure the iframe was loaded. Using load on document wouldn't ensure the iframe is loaded.

Of course, your iframe must have the same origin as the parent document (which also means you must open your file in http:// in your browser and not file://).

EDIT : Working demo