在iframe中调用javascript函数

sal*_*e55 58 javascript iframe

iframe在父页面中调用JavaScript函数时遇到问题.这是我的两页:

mainPage.html

<html>
<head>
    <title>MainPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            if (document.all.resultFrame)
                alert("resultFrame found");
            else
                alert("resultFrame NOT found");

            if (typeof (document.all.resultFrame.Reset) == "function")
                document.all.resultFrame.Reset();
            else
                alert("resultFrame.Reset NOT found");
        }
    </script>
</head>
<body>
    MainPage<br>
    <input type="button" onclick="Reset()" value="Reset"><br><br>
    <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

resultFrame.html

<html>
<head>
    <title>ResultPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            alert("reset (in resultframe)");
        }
    </script>
</head>
<body>
    ResultPage
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

(我知道document.all不推荐这个,但这个页面只能在内部用IE查看,我不认为这是问题)

当我按下重置按钮时,我得到"找到resultFrame"和"找不到resultFrame.Reset".它似乎有一个框架的引用,但不能调用框架上的功能,为什么会这样?

Jon*_*and 110

使用:

document.getElementById("resultFrame").contentWindow.Reset();
Run Code Online (Sandbox Code Playgroud)

访问iframe中的重置功能

document.getElementById("resultFrame") 将在您的代码中获取iframe,并将在iframe中contentWindow获取窗口对象.拥有子窗口后,您可以在该上下文中引用javascript.

另请参阅此处 特别是bobince的答案.

  • 嗨乔纳森,.contentWindow还能运作吗?我做`console.log(document.getElementById('iframeID').contentWindow)`并且在Firebug中它正确地在我的iframe中显示我的`test()`函数,但当我去调用函数时它说它不是函数, 但它是!在FF4中测试它. (3认同)

bar*_*ley 5

不要从文档中获取帧,而是尝试从窗口对象中获取帧.

在上面的例子中改变了这个:

if (typeof (document.all.resultFrame.Reset) == "function")
    document.all.resultFrame.Reset();
else
    alert("resultFrame.Reset NOT found");
Run Code Online (Sandbox Code Playgroud)

if (typeof (window.frames[0].Reset) == "function")
    window.frames[0].Reset();
else
    alert("resultFrame.Reset NOT found");
Run Code Online (Sandbox Code Playgroud)

问题是iframe中的javascript范围不是通过iframe的DOM元素公开的.只有窗口对象包含帧的javascript范围信息.


Dom*_*tin 5

为了更加健壮:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}
Run Code Online (Sandbox Code Playgroud)

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.reset();
  ...
}
...
Run Code Online (Sandbox Code Playgroud)