Calling a function inside an iframe from outside t

2019-02-12 13:15发布

This question already has an answer here:

I have a page with an iframe. Inside that iframe I have a javascript function like this:

function putme() {}

How can I call this function on the main page?

7条回答
Juvenile、少年°
2楼-- · 2019-02-12 13:53

For even more robustness:

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;
}

and

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

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.putme();
  ...
}
...
查看更多
登录 后发表回答