How do you post to an iframe?

前端 未结 4 2181
慢半拍i
慢半拍i 2020-11-22 00:55

How do you post data to an iframe?

4条回答
  •  野性不改
    2020-11-22 01:09

    If you want to change inputs in an iframe then submit the form from that iframe, do this

    ...
    var el = document.getElementById('targetFrame');
    
    var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below
    
    if (frame_win) {
      doc = (window.contentDocument || window.document);
    }
    
    if (doc) {
      doc.forms[0].someInputName.value = someValue;
      ...
      doc.forms[0].submit();
    }
    ...
    

    Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

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

提交回复
热议问题