JavaScript Ninja - IFRAME As HTML-To-DOM Parser

Posted at



Sample code may need more work. Create your own function using unique name, ID, and so forth.

var frame = document.getElementById("sample-frame");
if (!frame) {
// create frame
frame = document.createElement("iframe"); // iframe (or browser on older Firefox)
frame.setAttribute("id", "sample-frame");
frame.setAttribute("name", "sample-frame");
frame.setAttribute("type", "content");
frame.setAttribute("collapsed", "true");
document.getElementById("main-window")
.appendChild(frame);
// or
// document.documentElement.appendChild(frame);

// set restrictions as needed
frame.webNavigation.allowAuth = false;
frame.webNavigation.allowImages = false;
frame.webNavigation.allowJavascript = false;
frame.webNavigation.allowMetaRedirects = true;
frame.webNavigation.allowPlugins = false;
frame.webNavigation.allowSubframes = false;

// listen for load
frame.addEventListener("load", function (event) {
// the document of the HTML in the DOM
var doc = event.originalTarget;
// skip blank page or frame
if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return;

// do something with the DOM of doc
alert(doc.location.href);

// when done remove frame or set location "about:blank"
setTimeout(function () {
var frame = document.getElementById("sample-frame");
// remove frame
// frame.destroy(); // if using browser element instead of iframe
frame.parentNode.removeChild(frame);
// or set location "about:blank"
// frame.contentDocument.location.href = "about:blank";
}, 10);
}, true);
}


// load a page
frame.contentDocument.location.href = "http://www.mozilla.org/";
// or
// frame.webNavigation.loadURI("http://www.mozilla.org/",Components.interfaces.nsIWebNavigation,null,null,null);


If you are starting with an HTML string, you can convert it to a data URI and use that to load in the browser element.