parserHTML.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Regular Expressions for parsing tags and attributes
  2. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  3. var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  4. var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
  5. var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr,\n,\t,\t'); // Block Elements - HTML 5
  6. // fixed by xxx 将 ins 标签从块级名单中移除
  7. var block = makeMap('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'); // Inline Elements - HTML 5
  8. var inline = makeMap('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'); // Elements that you can, intentionally, leave open
  9. // (and which close themselves)
  10. var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
  11. var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected');
  12. // Special Elements (can contain anything)
  13. var special = makeMap('script,style');
  14. function HTMLParser(html, handler) {
  15. var index;
  16. var chars;
  17. var match;
  18. var stack = [];
  19. var last = html;
  20. stack.last = function () {
  21. return this[this.length - 1];
  22. };
  23. while (html) {
  24. chars = true; // Make sure we're not in a script or style element
  25. if (!stack.last() || !special[stack.last()]) {
  26. // Comment
  27. if (html.indexOf('<!--') == 0) {
  28. index = html.indexOf('-->');
  29. if (index >= 0) {
  30. if (handler.comment) {
  31. handler.comment(html.substring(4, index));
  32. }
  33. html = html.substring(index + 3);
  34. chars = false;
  35. } // end tag
  36. } else if (html.indexOf('</') == 0) {
  37. match = html.match(endTag);
  38. if (match) {
  39. html = html.substring(match[0].length);
  40. match[0].replace(endTag, parseEndTag);
  41. chars = false;
  42. } // start tag
  43. } else if (html.indexOf('<') == 0) {
  44. match = html.match(startTag);
  45. if (match) {
  46. html = html.substring(match[0].length);
  47. match[0].replace(startTag, parseStartTag);
  48. chars = false;
  49. }
  50. }
  51. if (chars) {
  52. index = html.indexOf('<');
  53. var text = index < 0 ? html : html.substring(0, index);
  54. html = index < 0 ? '' : html.substring(index);
  55. if (handler.chars) {
  56. handler.chars(text);
  57. }
  58. }
  59. } else {
  60. html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
  61. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
  62. if (handler.chars) {
  63. handler.chars(text);
  64. }
  65. return '';
  66. });
  67. parseEndTag('', stack.last());
  68. }
  69. if (html == last) {
  70. throw 'Parse Error: ' + html;
  71. }
  72. last = html;
  73. } // Clean up any remaining tags
  74. parseEndTag();
  75. function parseStartTag(tag, tagName, rest, unary) {
  76. tagName = tagName.toLowerCase();
  77. if (block[tagName]) {
  78. while (stack.last() && inline[stack.last()]) {
  79. parseEndTag('', stack.last());
  80. }
  81. }
  82. if (closeSelf[tagName] && stack.last() == tagName) {
  83. parseEndTag('', tagName);
  84. }
  85. unary = empty[tagName] || !!unary;
  86. if (!unary) {
  87. stack.push(tagName);
  88. }
  89. if (handler.start) {
  90. var attrs = [];
  91. rest.replace(attr, function (match, name) {
  92. var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
  93. attrs.push({
  94. name: name,
  95. value: value,
  96. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
  97. });
  98. });
  99. if (handler.start) {
  100. handler.start(tagName, attrs, unary);
  101. }
  102. }
  103. }
  104. function parseEndTag(tag, tagName) {
  105. // If no tag name is provided, clean shop
  106. if (!tagName) {
  107. var pos = 0;
  108. } // Find the closest opened tag of the same type
  109. else {
  110. for (var pos = stack.length - 1; pos >= 0; pos--) {
  111. if (stack[pos] == tagName) {
  112. break;
  113. }
  114. }
  115. }
  116. if (pos >= 0) {
  117. // Close all the open elements, up the stack
  118. for (var i = stack.length - 1; i >= pos; i--) {
  119. if (handler.end) {
  120. handler.end(stack[i]);
  121. }
  122. } // Remove the open elements from the stack
  123. stack.length = pos;
  124. }
  125. }
  126. }
  127. function makeMap(str) {
  128. var obj = {};
  129. var items = str.split(',');
  130. for (var i = 0; i < items.length; i++) {
  131. obj[items[i]] = true;
  132. }
  133. return obj;
  134. }
  135. function removeDOCTYPE(html) {
  136. return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
  137. }
  138. function parseAttrs(attrs) {
  139. return attrs.reduce(function (pre, attr) {
  140. var value = attr.value;
  141. var name = attr.name;
  142. if(value.indexOf('width') != -1){
  143. value += '; width:100%; height:auto;'
  144. }
  145. if (pre[name]) {
  146. pre[name] = pre[name] + " " + value;
  147. } else {
  148. pre[name] = value;
  149. }
  150. return pre;
  151. }, {});
  152. }
  153. function parseHtml(html) {
  154. html = removeDOCTYPE(html);
  155. html = html.replace(/\n/g,'');
  156. html = html.replace(/\t/g,'');
  157. var stacks = [];
  158. var results = {
  159. node : 'root',
  160. children: []
  161. };
  162. HTMLParser( html, {
  163. start : function start(tag, attrs, unary) {
  164. var node = {name: tag };
  165. if (attrs.length !== 0) {
  166. node.attrs = parseAttrs(attrs);
  167. }
  168. if (unary) {
  169. var parent = stacks[0] || results;
  170. if (!parent.children) {
  171. parent.children = [];
  172. }
  173. parent.children.push(node);
  174. } else {
  175. stacks.unshift(node);
  176. }
  177. },
  178. end: function end(tag) {
  179. var node = stacks.shift();
  180. if (node.name !== tag){console.error('invalid state: mismatch end tag');}
  181. if (stacks.length === 0) {
  182. results.children.push(node);
  183. } else {
  184. var parent = stacks[0];
  185. if (!parent.children) {
  186. parent.children = [];
  187. }
  188. parent.children.push(node);
  189. }
  190. },
  191. chars: function chars(text) {
  192. var node = {
  193. type: 'text',
  194. text: text
  195. };
  196. if (stacks.length === 0) {
  197. results.children.push(node);
  198. } else {
  199. var parent = stacks[0];
  200. if (!parent.children) {
  201. parent.children = [];
  202. }
  203. parent.children.push(node);
  204. }
  205. },
  206. comment: function comment(text) {
  207. var node = {
  208. node : 'comment',
  209. text : text
  210. };
  211. var parent = stacks[0];
  212. if (!parent.children) {
  213. parent.children = [];
  214. }
  215. parent.children.push(node);
  216. }
  217. });
  218. return results.children;
  219. }
  220. module.exports = {
  221. parserHTML : parseHtml
  222. }