Invoking JavaScript code in an iframe from the parent page

后端 未结 17 1795
栀梦
栀梦 2020-11-21 07:00

Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the o

17条回答
  •  执笔经年
    2020-11-21 07:11

    Folowing Nitin Bansal's answer

    and 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.targetFunction();
      ...
    }
    ...
    

提交回复
热议问题