访问iframe函数

Access iframe functions

本文关键字:函数 iframe 访问      更新时间:2023-09-26

这个问题似乎只发生在chrome中这是iframe代码

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

这就是我创建iframe 的方式

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

然后我试着调用iframe的blablah()函数:

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

但这不起作用

这是有效的:

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

请注意,我使用了$(window).load来确保已加载iframe。在document上使用load并不能确保iframe被加载。

当然,您的iframe必须与父文档具有相同的来源(这也意味着您必须在浏览器中的http://而不是file://中打开文件)。

编辑:工作演示