Snippet. JavaScript. Read Content of IFrame

This small JavaScript snippet shows how to read the content of an IFrame.

Function iframe_get_text

function iframe_get_text(iframe) {
  var doc = null;
  if (iframe.contentDocument) { // For NS6
    doc = iframe.contentDocument; 
  } else if (iframe.contentWindow) { // For IE5.5 and IE6
    doc = iframe.contentWindow.document;
  } else if (iframe.document) { // For IE5
    doc = iframe.document;
  } else {
    return null;
  }
  return doc.body;
}

Example

var iframe = document.getElementById("my_iframe");

var text = iframe_get_text(iframe);

Updated on: 28 Mar 2024