Although you can now natively parse HTML using DOMParser and XMLHttpRequest, this is a new feature that is not yet supported by all browsers in use in the wild. The code snippets on this page will let your site work until these new features are more widely available.

Safely parsing simple HTML to DOM

When using XMLHttpRequest to get the HTML of a remote webpage, it is often advantageous to turn that HTML string into DOM for easier manipulation. However, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the HTML safely.

The function below will safely parse simple HTML and return a DOM object which can be manipulated like web page elements. This will remove tags like <script>, <style>, <head>, <body>, <title>, and <iframe>. It will also remove all JavaScript, including element attributes that contain JavaScript.

function HTMLParser(aHTMLString){
var html = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", null),
body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
html.documentElement.appendChild(body); body.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"].getService(Components.interfaces.nsIScriptableUnescapeHTML).parseFragment(aHTMLString, false, null, body)); return body;
},

It works by creating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the HTML fragment and attaching that fragment to the <div>. The <div> is returned, and it is never actually appended to the current page. The returned <body> object is of type Element

Here is a sample that counts the number of paragraphs in a string:

var DOMPars = HTMLParser('<p>foo</p><p>bar</p>');
alert(DOMPars.getElementsByTagName('p').length);

If method HTMLParser() returns variable html (instead of body), you have all document object with its complete functions list, therefore you can retrieve info within div tag like this:

var DOMPars = HTMLParser("<div id='userInfo'>John was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>");
alert(DOMPars.getElementById('userInfo').innerHTML);

To parse a complete HTML page, load it into an iframe whose type is content (not chrome). See Using a hidden iframe element to parse HTML to a window's DOM below.

Parsing Complete HTML to DOM

Loading an html document seems much more simpler if its loaded using the XMLHttpRequest object. For that matter we are going to load our HTML document first:

var request = XMLHttpRequest();
request.open("GET", "http://example.org/file.html", false);
request.send(null);

our next step is to create the DOM that we need to feed our newly gathered html information:

var doc = document.implementation.createHTMLDocument("example");
doc.documentElement.innerHTML = request.responseText;

after this any manipulation that we might want to do will be something as simple as the following:

doc.body.textContent = "This is inside the body!";

Using a hidden iframe element to parse HTML to a window's DOM

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.

Using a hidden XUL iframe (alternate example)

Sometimes, a browser element is overkill, or does not meet your needs, or you can't fulfill its requirements. While working on Donkeyfire, I discovered the iframe XUL element, and it is very easy to implement it.

As an example, I will show a browser overlay .xul file, and some JavaScript code to access it.

Here is some XUL code you can add to your browser overlay .xul file. Don't forget to modify the id and name!

<vbox hidden="false" height="0">
<iframe type="content" src="" name="donkey-browser" hidden="false" id="donkey-browser" height="0"/>
</vbox>

Then, in your extension's "load" event handler:

onLoad: function() {
donkeybrowser = document.getElementById("donkey-browser");
if (donkeybrowser) {
donkeybrowser.style.height = "0px";
donkeybrowser.webNavigation.allowAuth = true;
donkeybrowser.webNavigation.allowImages = false;
donkeybrowser.webNavigation.allowJavascript = false;
donkeybrowser.webNavigation.allowMetaRedirects = true;
donkeybrowser.webNavigation.allowPlugins = false;
donkeybrowser.webNavigation.allowSubframes = false;
donkeybrowser.addEventListener("DOMContentLoaded", function (e) { donkeyfire.donkeybrowser_onPageLoad(e); }, true);
}

With that code, we obtain a reference to the iframe element we declared in the .xul file. The most interesting piece of code here is the DOMContentLoaded event listener we define for the element. Let's take a look at the donkeyfire.donkeybrowser_onPageLoad() handler:

donkeybrowser_onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget;
var url = doc.location.href;
if (aEvent.originalTarget.nodeName == "#document") { // ok, it's a real page, let's do our magic
dump("[DF] URL = "+url+"\n");
var text = doc.evaluate("/html/body/h1",doc,null,XPathResult.STRING_TYPE,null).stringValue;
dump("[DF] TEXT in /html/body/h1 = "+text+"\n");
}
},

As you can see, we obtain full access to the DOM of the page we loaded in background, and we can even evaluate XPath expressions. In the example, we dump() to the console the page's URL and the text contained in the first h1 tag of the page's <body>.

But, we still need to see how to execute the famous loadURI() method using our iframe:

donkeybrowser.webNavigation.loadURI("http://developer.mozilla.org",Components.interfaces.nsIWebNavigation, null, null, null);

Also, I recommend you take a look at the nsIWebNavigation interface.

来自MDNhttps://developer.mozilla.org/en-US/Add-ons/Code_snippets/HTML_to_DOM,应该比较完整了。

HTML to DOM的更多相关文章

  1. 关于DOM的操作以及性能优化问题-重绘重排

     写在前面: 大家都知道DOM的操作很昂贵. 然后贵在什么地方呢? 一.访问DOM元素 二.修改DOM引起的重绘重排 一.访问DOM 像书上的比喻:把DOM和JavaScript(这里指ECMScri ...

  2. 读书笔记:JavaScript DOM 编程艺术(第二版)

    读完还是能学到很多的基础知识,这里记录下,方便回顾与及时查阅. 内容也有自己的一些补充. JavaScript DOM 编程艺术(第二版) 1.JavaScript简史 JavaScript由Nets ...

  3. 页面嵌入dom与被嵌入iframe的攻防

    1.情景一:自己的页面被引入(嵌入)至别人的页面iframe中 if(window.self != window.top){ //url是自己页面的url window.top.location.hr ...

  4. 通俗易懂的来讲讲DOM

    DOM是所有前端开发每天打交道的东西,但是随着jQuery等库的出现,大大简化了DOM操作,导致大家慢慢的“遗忘”了它的本来面貌.不过,要想深入学习前端知识,对DOM的了解是不可或缺的,所以本文力图系 ...

  5. HTML DOM 介绍

    本篇主要介绍DOM内容.DOM 节点.节点属性以及获取HTML元素的方法. 目录 1. 介绍 DOM:介绍DOM,以及对DOM分类和功能的说明. 2. DOM 节点:介绍DOM节点分类和节点层次. 3 ...

  6. HTML DOM 对象

    本篇主要介绍HTML DOM 对象:Document.Element.Attr.Event等4个对象. 目录 1. Document 对象:表示文档树的根节点,大部分属性和方法都是对元素进行操作. 2 ...

  7. 重撸js_2_基础dom操作

    1.node 方法 返回 含义 nodeName String 获取节点名称 nodeType Number 获取节点类型 nodeValue String 节点的值(注意:文本也是节点) 2.inn ...

  8. 虚拟dom与diff算法 分析

    好文集合: 深入浅出React(四):虚拟DOM Diff算法解析 全面理解虚拟DOM,实现虚拟DOM

  9. 窥探Vue.js 2.0 - Virtual DOM到底是个什么鬼?

    引言 你可能听说在Vue.js 2.0已经发布,并且在其中新添加如了一些新功能.其中一个功能就是"Virtual DOM". Virtual DOM是什么 在之前,React和Em ...

  10. jQuery学习之路(2)-DOM操作

    ▓▓▓▓▓▓ 大致介绍 jQuery作为JavaScript库,继承并发扬了JavaScript对DOM对象操作的特性,使开发人员能方便的操作DOM对象. ▓▓▓▓▓▓ jQuery中的DOM操作 看 ...

随机推荐

  1. Android Window 9问9答

    1.简述一下window是什么?在android体系里 扮演什么角色? 答:window就是一个抽象类,他的实现类是phoneWindow.我们一般通过windowManager 来访问window. ...

  2. 【转】ios开发之AppDelegate

    创建应用程序之后之后,默认有AppDelegate.h文件与AppDelegate.m文件.   AppDelegate为何物?  AppDelegate为整个应用的一个代理,提供程序启动.退出等类似 ...

  3. Eclipse中安装可以新建html文件的插件(Eclipse HTML Editor)

    最近在eclipse中开发android项目,用到了jquery mobile框架,则会涉及到新建html文件,发现eclipse不自带新建html文件的插件,必须得新建一个其他形式的文件,譬如xml ...

  4. 嵌入式 RTSP流媒体播放器实现

    最近需要做一个RTSP流媒体播放器,研究了一下,封装了一个RTSP播放类CRTSPPlayer,解码库采用ffmpeg.由于需求比较简单,时间也有限,目前只实现了播放.停止.暂停几个基本的接口.下面是 ...

  5. [Papers]MHD, $\p_3\pi$, Lebesgue space [Jia-Zhou, JMAA, 2012]

    $$\bex \p_3\pi\in L^p(0,T;L^q(\bbR^3)),\quad \frac{2}{p}+\frac{3}{q}=2,\quad 3\leq q\leq \infty. \ee ...

  6. Aptana 插件 for Eclipse 4.4

    http://download.aptana.com/studio3/plugin/install Aptana Update Site This site is designed to be use ...

  7. ubuntu 挂起唤醒和声音偏小的问题

    自从开始用ubuntu就遇到了声音偏小的问题,一直很让我头疼.还好插上耳机后勉强能用,也就没继续追究了. 可最近发现了一个更加严重的问题挂起后竟然无法唤醒,一直是黑屏的状态,必须强制关机再重启,这就蛋 ...

  8. qt信号signal和槽slot机制

    内容: 一.概述 二.信号 三.槽 四.信号与槽的关联 五.元对象工具 六.程序样例 七.应注意的问题 信号与槽作为QT的核心机制在QT编程中有着广泛的应用,本文介绍了信号与槽的一些基本概念.元对象工 ...

  9. 【转】SQL Server 数据库内部版本号

    -----------数据库还原或版本升级出现版本错误时可参考. Internal SQL Server Database Version Numbers A database created by ...

  10. NServiceBus教程-NServiceBus和WCF

    WCF中缺少的最主要的事情是发布/订阅,但为什么你必须建立它自己吗?NServiceBus,你把它弄出来. 下一个重要的事情是容错.异常导致WCF代理休息,需要"刷新"的代码,但调 ...