html2json.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**
  2. * html2Json 改造来自: https://github.com/Jxck/html2json
  3. *
  4. *
  5. * author: Di (微信小程序开发工程师)
  6. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  7. * 垂直微信小程序开发交流社区
  8. *
  9. * github地址: https://github.com/icindy/wxParse
  10. *
  11. * for: 微信小程序富文本解析
  12. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  13. */
  14. import wxDiscode from './wxDiscode';
  15. import HTMLParser from './htmlparser';
  16. function makeMap(str) {
  17. const obj = {};
  18. const items = str.split(',');
  19. for (let i = 0; i < items.length; i += 1) obj[items[i]] = true;
  20. return obj;
  21. }
  22. // Block Elements - HTML 5
  23. const block = makeMap(
  24. 'br,code,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,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'
  25. );
  26. // Inline Elements - HTML 5
  27. const inline = makeMap(
  28. 'a,abbr,acronym,applet,b,basefont,bdo,big,button,cite,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'
  29. );
  30. // Elements that you can, intentionally, leave open
  31. // (and which close themselves)
  32. const closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
  33. function removeDOCTYPE(html) {
  34. const isDocument = /<body.*>([^]*)<\/body>/.test(html);
  35. return isDocument ? RegExp.$1 : html;
  36. }
  37. function trimHtml(html) {
  38. return html
  39. .replace(/<!--.*?-->/gi, '')
  40. .replace(/\/\*.*?\*\//gi, '')
  41. // .replace(/[ ]+</gi, '<')
  42. .replace(/<script[^]*<\/script>/gi, '')
  43. .replace(/<style[^]*<\/style>/gi, '');
  44. }
  45. function getScreenInfo() {
  46. const screen = {};
  47. wx.getSystemInfo({
  48. success: (res) => {
  49. screen.width = res.windowWidth;
  50. screen.height = res.windowHeight;
  51. },
  52. });
  53. return screen;
  54. }
  55. function html2json(html, customHandler, imageProp, host) {
  56. // 处理字符串
  57. html = removeDOCTYPE(html);
  58. html = trimHtml(html);
  59. html = wxDiscode.strDiscode(html);
  60. // 生成node节点
  61. const bufArray = [];
  62. const results = {
  63. nodes: [],
  64. imageUrls: [],
  65. };
  66. const screen = getScreenInfo();
  67. function Node(tag) {
  68. this.node = 'element';
  69. this.tag = tag;
  70. this.$screen = screen;
  71. }
  72. HTMLParser(html, {
  73. start(tag, attrs, unary) {
  74. // node for this element
  75. const node = new Node(tag);
  76. if (bufArray.length !== 0) {
  77. const parent = bufArray[0];
  78. if (parent.nodes === undefined) {
  79. parent.nodes = [];
  80. }
  81. }
  82. if (block[tag]) {
  83. node.tagType = 'block';
  84. } else if (inline[tag]) {
  85. node.tagType = 'inline';
  86. } else if (closeSelf[tag]) {
  87. node.tagType = 'closeSelf';
  88. }
  89. node.attr = attrs.reduce((pre, attr) => {
  90. const {
  91. name
  92. } = attr;
  93. let {
  94. value
  95. } = attr;
  96. if (name === 'class') {
  97. node.classStr = value;
  98. }
  99. // has multi attibutes
  100. // make it array of attribute
  101. if (name === 'style') {
  102. node.styleStr = value;
  103. }
  104. if (value.match(/ /)) {
  105. value = value.split(' ');
  106. }
  107. // if attr already exists
  108. // merge it
  109. if (pre[name]) {
  110. if (Array.isArray(pre[name])) {
  111. // already array, push to last
  112. pre[name].push(value);
  113. } else {
  114. // single value, make it array
  115. pre[name] = [pre[name], value];
  116. }
  117. } else {
  118. // not exist, put it
  119. pre[name] = value;
  120. }
  121. return pre;
  122. }, {});
  123. // 优化样式相关属性
  124. if (node.classStr) {
  125. node.classStr += ` ${node.tag}`;
  126. } else {
  127. node.classStr = node.tag;
  128. }
  129. if (node.tagType === 'inline') {
  130. node.classStr += ' inline';
  131. }
  132. // 对img添加额外数据
  133. if (node.tag === 'img') {
  134. let imgUrl = node.attr.src;
  135. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, imageProp.domain);
  136. Object.assign(node.attr, imageProp, {
  137. src: imgUrl || '',
  138. });
  139. if (imgUrl) {
  140. results.imageUrls.push(imgUrl);
  141. }
  142. }
  143. // 处理a标签属性
  144. if (node.tag === 'a') {
  145. node.attr.href = node.attr.href || '';
  146. }
  147. //处理table
  148. if (node.tag === 'table' || node.tag === 'tr' || node.tag === 'td') {
  149. node.styleStr = ""
  150. if (node.attr.width) {
  151. node.styleStr += "width:" + node.attr.width + 'px;'
  152. if (node.attr.width > node.$screen.width) {
  153. //等比缩放height
  154. if (node.attr.height) {
  155. node.attr.height = (node.$screen.width * node.attr.height) / node.attr.width
  156. }
  157. }
  158. }
  159. if (node.attr.height) {
  160. node.styleStr += "height:" + node.attr.height + 'px;'
  161. }
  162. }
  163. //处理video
  164. if (node.tag === 'video') {
  165. node.styleStr = ""
  166. if (node.attr.width) {
  167. node.styleStr += "width:" + node.attr.width + 'px;'
  168. if (node.attr.width > node.$screen.width) {
  169. //等比缩放height
  170. if (node.attr.height) {
  171. node.attr.height = (node.$screen.width * node.attr.height) / node.attr.width
  172. }
  173. }
  174. }
  175. if (node.attr.height) {
  176. node.styleStr += "height:" + node.attr.height + 'px;'
  177. }
  178. }
  179. // 处理font标签样式属性
  180. if (node.tag === 'font') {
  181. const fontSize = [
  182. 'x-small',
  183. 'small',
  184. 'medium',
  185. 'large',
  186. 'x-large',
  187. 'xx-large',
  188. '-webkit-xxx-large',
  189. ];
  190. const styleAttrs = {
  191. color: 'color',
  192. face: 'font-family',
  193. size: 'font-size',
  194. };
  195. if (!node.styleStr) node.styleStr = '';
  196. Object.keys(styleAttrs).forEach((key) => {
  197. if (node.attr[key]) {
  198. const value = key === 'size' ? fontSize[node.attr[key] - 1] : node.attr[key];
  199. node.styleStr += `${styleAttrs[key]}: ${value};`;
  200. }
  201. });
  202. }
  203. // 临时记录source资源
  204. if (node.tag === 'source') {
  205. results.source = node.attr.src;
  206. }
  207. //#ifndef MP-BAIDU
  208. if (customHandler.start) {
  209. customHandler.start(node, results);
  210. }
  211. //#endif
  212. if (unary) {
  213. // if this tag doesn't have end tag
  214. // like <img src="hoge.png"/>
  215. // add to parents
  216. const parent = bufArray[0] || results;
  217. if (parent.nodes === undefined) {
  218. parent.nodes = [];
  219. }
  220. parent.nodes.push(node);
  221. } else {
  222. bufArray.unshift(node);
  223. }
  224. },
  225. end(tag) {
  226. // merge into parent tag
  227. const node = bufArray.shift();
  228. if (node.tag !== tag) {
  229. console.error('invalid state: mismatch end tag');
  230. }
  231. // 当有缓存source资源时于于video补上src资源
  232. if (node.tag === 'video' && results.source) {
  233. node.attr.src = results.source;
  234. delete results.source;
  235. }
  236. //#ifndef MP-BAIDU
  237. if (customHandler && customHandler.end) {
  238. customHandler.end(node, results);
  239. }
  240. //#endif
  241. if (bufArray.length === 0) {
  242. results.nodes.push(node);
  243. } else {
  244. const parent = bufArray[0];
  245. if (!parent.nodes) {
  246. parent.nodes = [];
  247. }
  248. parent.nodes.push(node);
  249. }
  250. },
  251. chars(text) {
  252. if (!text.trim()) return;
  253. const node = {
  254. node: 'text',
  255. text,
  256. };
  257. //#ifndef MP-BAIDU
  258. if (customHandler.chars) {
  259. customHandler.chars(node, results);
  260. }
  261. //#endif
  262. if (bufArray.length === 0) {
  263. results.nodes.push(node);
  264. } else {
  265. const parent = bufArray[0];
  266. if (parent.nodes === undefined) {
  267. parent.nodes = [];
  268. }
  269. parent.nodes.push(node);
  270. }
  271. },
  272. });
  273. return results;
  274. }
  275. export default html2json;