html-parser.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * HTML5 Parser By Sam Blowes
  3. *
  4. * Designed for HTML5 documents
  5. *
  6. * Original code by John Resig (ejohn.org)
  7. * http://ejohn.org/blog/pure-javascript-html-parser/
  8. * Original code by Erik Arvidsson, Mozilla Public License
  9. * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
  10. *
  11. * ----------------------------------------------------------------------------
  12. * License
  13. * ----------------------------------------------------------------------------
  14. *
  15. * This code is triple licensed using Apache Software License 2.0,
  16. * Mozilla Public License or GNU Public License
  17. *
  18. * ////////////////////////////////////////////////////////////////////////////
  19. *
  20. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  21. * use this file except in compliance with the License. You may obtain a copy
  22. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  23. *
  24. * ////////////////////////////////////////////////////////////////////////////
  25. *
  26. * The contents of this file are subject to the Mozilla Public License
  27. * Version 1.1 (the "License"); you may not use this file except in
  28. * compliance with the License. You may obtain a copy of the License at
  29. * http://www.mozilla.org/MPL/
  30. *
  31. * Software distributed under the License is distributed on an "AS IS"
  32. * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  33. * License for the specific language governing rights and limitations
  34. * under the License.
  35. *
  36. * The Original Code is Simple HTML Parser.
  37. *
  38. * The Initial Developer of the Original Code is Erik Arvidsson.
  39. * Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
  40. * Reserved.
  41. *
  42. * ////////////////////////////////////////////////////////////////////////////
  43. *
  44. * This program is free software; you can redistribute it and/or
  45. * modify it under the terms of the GNU General Public License
  46. * as published by the Free Software Foundation; either version 2
  47. * of the License, or (at your option) any later version.
  48. *
  49. * This program is distributed in the hope that it will be useful,
  50. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  51. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  52. * GNU General Public License for more details.
  53. *
  54. * You should have received a copy of the GNU General Public License
  55. * along with this program; if not, write to the Free Software
  56. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  57. *
  58. * ----------------------------------------------------------------------------
  59. * Usage
  60. * ----------------------------------------------------------------------------
  61. *
  62. * // Use like so:
  63. * HTMLParser(htmlString, {
  64. * start: function(tag, attrs, unary) {},
  65. * end: function(tag) {},
  66. * chars: function(text) {},
  67. * comment: function(text) {}
  68. * });
  69. *
  70. * // or to get an XML string:
  71. * HTMLtoXML(htmlString);
  72. *
  73. * // or to get an XML DOM Document
  74. * HTMLtoDOM(htmlString);
  75. *
  76. * // or to inject into an existing document/DOM node
  77. * HTMLtoDOM(htmlString, document);
  78. * HTMLtoDOM(htmlString, document.body);
  79. *
  80. */
  81. // Regular Expressions for parsing tags and attributes
  82. var startTag =
  83. /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  84. var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  85. var attr =
  86. /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
  87. var empty = makeMap(
  88. 'area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
  89. // fixed by xxx 将 ins 标签从块级名单中移除
  90. var block = makeMap(
  91. 'a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'
  92. ); // Inline Elements - HTML 5
  93. var inline = makeMap(
  94. 'abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'
  95. ); // Elements that you can, intentionally, leave open
  96. // (and which close themselves)
  97. var closeSelf = makeMap(
  98. 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
  99. var fillAttrs = makeMap(
  100. 'checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'
  101. ); // Special Elements (can contain anything)
  102. var special = makeMap('script,style');
  103. function HTMLParser(html, handler) {
  104. var index;
  105. var chars;
  106. var match;
  107. var stack = [];
  108. var last = html;
  109. stack.last = function() {
  110. return this[this.length - 1];
  111. };
  112. while (html) {
  113. chars = true; // Make sure we're not in a script or style element
  114. if (!stack.last() || !special[stack.last()]) {
  115. // Comment
  116. if (html.indexOf('<!--') == 0) {
  117. index = html.indexOf('-->');
  118. if (index >= 0) {
  119. if (handler.comment) {
  120. handler.comment(html.substring(4, index));
  121. }
  122. html = html.substring(index + 3);
  123. chars = false;
  124. } // end tag
  125. } else if (html.indexOf('</') == 0) {
  126. match = html.match(endTag);
  127. if (match) {
  128. html = html.substring(match[0].length);
  129. match[0].replace(endTag, parseEndTag);
  130. chars = false;
  131. } // start tag
  132. } else if (html.indexOf('<') == 0) {
  133. match = html.match(startTag);
  134. if (match) {
  135. html = html.substring(match[0].length);
  136. match[0].replace(startTag, parseStartTag);
  137. chars = false;
  138. }
  139. }
  140. if (chars) {
  141. index = html.indexOf('<');
  142. var text = index < 0 ? html : html.substring(0, index);
  143. html = index < 0 ? '' : html.substring(index);
  144. if (handler.chars) {
  145. handler.chars(text);
  146. }
  147. }
  148. } else {
  149. html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function(all, text) {
  150. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
  151. if (handler.chars) {
  152. handler.chars(text);
  153. }
  154. return '';
  155. });
  156. parseEndTag('', stack.last());
  157. }
  158. if (html == last) {
  159. throw 'Parse Error: ' + html;
  160. }
  161. last = html;
  162. } // Clean up any remaining tags
  163. parseEndTag();
  164. function parseStartTag(tag, tagName, rest, unary) {
  165. tagName = tagName.toLowerCase();
  166. if (block[tagName]) {
  167. while (stack.last() && inline[stack.last()]) {
  168. parseEndTag('', stack.last());
  169. }
  170. }
  171. if (closeSelf[tagName] && stack.last() == tagName) {
  172. parseEndTag('', tagName);
  173. }
  174. unary = empty[tagName] || !!unary;
  175. if (!unary) {
  176. stack.push(tagName);
  177. }
  178. if (handler.start) {
  179. var attrs = [];
  180. rest.replace(attr, function(match, name) {
  181. var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ?
  182. arguments[4] : fillAttrs[name] ? name : '';
  183. attrs.push({
  184. name: name,
  185. value: value,
  186. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
  187. });
  188. });
  189. if (handler.start) {
  190. handler.start(tagName, attrs, unary);
  191. }
  192. }
  193. }
  194. function parseEndTag(tag, tagName) {
  195. // If no tag name is provided, clean shop
  196. if (!tagName) {
  197. var pos = 0;
  198. } // Find the closest opened tag of the same type
  199. else {
  200. for (var pos = stack.length - 1; pos >= 0; pos--) {
  201. if (stack[pos] == tagName) {
  202. break;
  203. }
  204. }
  205. }
  206. if (pos >= 0) {
  207. // Close all the open elements, up the stack
  208. for (var i = stack.length - 1; i >= pos; i--) {
  209. if (handler.end) {
  210. handler.end(stack[i]);
  211. }
  212. } // Remove the open elements from the stack
  213. stack.length = pos;
  214. }
  215. }
  216. }
  217. function makeMap(str) {
  218. var obj = {};
  219. var items = str.split(',');
  220. for (var i = 0; i < items.length; i++) {
  221. obj[items[i]] = true;
  222. }
  223. return obj;
  224. }
  225. function removeDOCTYPE(html) {
  226. return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
  227. }
  228. function parseAttrs(attrs) {
  229. return attrs.reduce(function(pre, attr) {
  230. var value = attr.value;
  231. var name = attr.name;
  232. if (pre[name]) {
  233. pre[name] = pre[name] + " " + value;
  234. } else {
  235. pre[name] = value;
  236. }
  237. return pre;
  238. }, {});
  239. }
  240. function parseHtml(html) {
  241. html = removeDOCTYPE(html);
  242. var stacks = [];
  243. var results = {
  244. node: 'root',
  245. children: []
  246. };
  247. HTMLParser(html, {
  248. start: function start(tag, attrs, unary) {
  249. var node = {
  250. name: tag
  251. };
  252. if (attrs.length !== 0) {
  253. node.attrs = parseAttrs(attrs);
  254. }
  255. if (unary) {
  256. var parent = stacks[0] || results;
  257. if (!parent.children) {
  258. parent.children = [];
  259. }
  260. parent.children.push(node);
  261. } else {
  262. stacks.unshift(node);
  263. }
  264. },
  265. end: function end(tag) {
  266. var node = stacks.shift();
  267. if (node.name !== tag) console.error('invalid state: mismatch end tag');
  268. if (stacks.length === 0) {
  269. results.children.push(node);
  270. } else {
  271. var parent = stacks[0];
  272. if (!parent.children) {
  273. parent.children = [];
  274. }
  275. parent.children.push(node);
  276. }
  277. },
  278. chars: function chars(text) {
  279. var node = {
  280. type: 'text',
  281. text: text
  282. };
  283. if (stacks.length === 0) {
  284. results.children.push(node);
  285. } else {
  286. var parent = stacks[0];
  287. if (!parent.children) {
  288. parent.children = [];
  289. }
  290. parent.children.push(node);
  291. }
  292. },
  293. comment: function comment(text) {
  294. var node = {
  295. node: 'comment',
  296. text: text
  297. };
  298. var parent = stacks[0];
  299. if (!parent.children) {
  300. parent.children = [];
  301. }
  302. parent.children.push(node);
  303. }
  304. });
  305. return results.children;
  306. }
  307. export default parseHtml;