Parse HTML Safely

Source: Internet
Author: User

Parse HTML Safely

JQuery. parseHTML

How can I convert an HTML code into a DOM tree for processing?

If you usejQuery, You can use its $. parseHTML method to convert HTML code into a DOM tree.

var markup = '

' + '' + '<script type="text/javascript">' + 'document.onclick=function(){console.log("click");};' + 'window.alert("hello");' + 'document.write("hello");' + '</script>' + '

', domArray = $.parseHTML(markup); window.console.log(domArray);


Looking at jQuery's source code, its parse HTML principle is consistent with the following code:

    /**     * @param {String} markup     * @param {Document} [context]     * @return {Array}     */var parseHTMLWithDiv = function (markup, context) {        context = context || document;        var wrapper = context.createElement('div'),            domArray = [],            index,            len;        wrapper.innerHTML = markup;        len = wrapper.childNodes.length;        for (index = 0; index < len; index++) {            domArray.push(wrapper.childNodes[index]);        }        return domArray;    };


You can also place HTML content in a hidden iframe for parse.

/** * @param {String} markup * @param {Document} [context] * @return {Array} */var parseHTMLWithIframe = function (markup, context) {    context = context || document;    var iframe = context.createElement('iframe'),        body,        index,        len,        domArray = [];    iframe.src = '';    iframe.style.display = 'none';    context.body.appendChild(iframe);    body = iframe.contentDocument.body;    body.innerHTML = markup;    len = body.childNodes.length;    for (index = 0; index < len; index++) {        domArray.push(body.childNodes[index]);    }    context.body.removeChild(iframe);    return domArray;}


If you observe the parse HTML process carefully, you can find the following points:

  1. Scripts in HTML code are not executed
    • Security Assurance
    • The browser automatically sends an image src request to pre-load the image.
      • When div is used, the image is pre-loaded.
      • When iframe is used, the image loading request is sent, but the DOMParser is canceled.

        If the HTML code after parse does not need to be injected into the page, the browser automatically sends an image src request during the parse HTML process to occupy resources such as network requests, which is not perfect.

        What should we do to prevent the browser from automatically sending an image src request?

        In jQuery$.parseHTML()A similar method is called$.parseXML()For parse xml. view the source code:

        // Cross-browser xml parsingjQuery.parseXML = function( data ) {    var xml, tmp;    if ( !data || typeof data !== "string" ) {        return null;    }    // Support: IE9    try {        tmp = new DOMParser();        xml = tmp.parseFromString( data, "text/xml" );    } catch ( e ) {        xml = undefined;    }    if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {        jQuery.error( "Invalid XML: " + data );    }    return xml;};


        JQuery uses DOMParser to parse the XML document. DOMParser can not only parse the XML document, but also parse the HTML document.

        enum SupportedType {  "text/html",  "text/xml",  "application/xml",  "application/xhtml+xml",  "image/svg+xml"};[Constructor]interface DOMParser {  Document parseFromString(DOMString str, SupportedType type);};


        When using DOMParser to analyze HTML documents, the browser will not automatically send a request for image src. in browsers that do not support DOMParser, there is an alternative solution: DOMImplementation. createHTMLDocument

        /** * There are two ways to parse html snippet: * 1. parse html in a virtual Document/DOMParser object. * 2. create a `div` element as wrapper and set html as its innerHTML. * * The 1st way can prevent loading images that in the html and is safer. * * NOTE:  This function does not support ie8 and ie8- * * @param {String} markup the html string that can be set as the  innserHTML * @param {Document} [context] * of  * @return {Document} if returned value is null, you can follow the 2ed way. */function parseHTML(markup, context) {    var doc,        parser,        win;    context = context || document;    if (context.implementation &&            context.implementation.createHTMLDocument) {        doc = context.implementation.createHTMLDocument();        doc.body.innerHTML = markup;        return doc;    }    win = context.defaultView || window;    if (win.DOMParser) {        parser = new win.DOMParser();        try {            doc = parser.parseFromString('', 'text/html');        } catch (ex) {            // do nothing        }        if (doc) {            doc.body.innerHTML = markup;            return doc;        }    }};


        Reference
        1. Https://code.google.com/p/google-caja/issues/detail? Id = 1823
        2. Http://api.jquery.com/jquery.parsehtml/
        3. Https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
        4. Http://domparsing.spec.whatwg.org/
        5. Https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.