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:
- 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
- Https://code.google.com/p/google-caja/issues/detail? Id = 1823
- Http://api.jquery.com/jquery.parsehtml/
- Https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
- Http://domparsing.spec.whatwg.org/
- Https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument