html2json.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. var __placeImgeUrlHttps = "https";
  15. var __emojisReg = '';
  16. var __emojisBaseSrc = '';
  17. var __emojis = {};
  18. var imagedomain = "http://127.0.0.1:8080"; //替换为自己的实际IP地址
  19. var wxDiscode = require('./wxDiscode.js');
  20. var HTMLParser = require('./htmlparser.js');
  21. // Empty Elements - HTML 5
  22. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  23. // Block Elements - HTML 5
  24. var block = makeMap("br,a,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. // Inline Elements - HTML 5
  26. var inline = makeMap("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");
  27. // Elements that you can, intentionally, leave open
  28. // (and which close themselves)
  29. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  30. // Attributes that have their values filled in disabled="disabled"
  31. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  32. // Special Elements (can contain anything)
  33. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  34. function makeMap(str) {
  35. var obj = {}, items = str.split(",");
  36. for (var i = 0; i < items.length; i++)
  37. obj[items[i]] = true;
  38. return obj;
  39. }
  40. function q(v) {
  41. return '"' + v + '"';
  42. }
  43. function removeDOCTYPE(html) {
  44. return html
  45. .replace(/<\?xml.*\?>\n/, '')
  46. .replace(/<.*!doctype.*\>\n/, '')
  47. .replace(/<.*!DOCTYPE.*\>\n/, '');
  48. }
  49. function html2json(html, bindName) {
  50. //处理字符串
  51. html = removeDOCTYPE(html);
  52. html = wxDiscode.strDiscode(html);
  53. //生成node节点
  54. var bufArray = [];
  55. var results = {
  56. node: bindName,
  57. nodes: [],
  58. images:[],
  59. imageUrls:[]
  60. };
  61. HTMLParser(html, {
  62. start: function (tag, attrs, unary) {
  63. //debug(tag, attrs, unary);
  64. // node for this element
  65. var node = {
  66. node: 'element',
  67. tag: tag,
  68. };
  69. if (block[tag]) {
  70. node.tagType = "block";
  71. } else if (inline[tag]) {
  72. node.tagType = "inline";
  73. } else if (closeSelf[tag]) {
  74. node.tagType = "closeSelf";
  75. }
  76. if (attrs.length !== 0) {
  77. node.attr = attrs.reduce(function (pre, attr) {
  78. var name = attr.name;
  79. var value = attr.value;
  80. if (name == 'class') {
  81. console.dir(value);
  82. // value = value.join("")
  83. node.classStr = value;
  84. }
  85. // has multi attibutes
  86. // make it array of attribute
  87. if (name == 'style') {
  88. console.dir(value);
  89. // value = value.join("")
  90. node.styleStr = value;
  91. }
  92. if (value.match(/ /)) {
  93. value = value.split(' ');
  94. }
  95. // if attr already exists
  96. // merge it
  97. if (pre[name]) {
  98. if (Array.isArray(pre[name])) {
  99. // already array, push to last
  100. pre[name].push(value);
  101. } else {
  102. // single value, make it array
  103. pre[name] = [pre[name], value];
  104. }
  105. } else {
  106. // not exist, put it
  107. pre[name] = value;
  108. }
  109. return pre;
  110. }, {});
  111. }
  112. //对img添加额外数据
  113. if (node.tag === 'img') {
  114. node.imgIndex = results.images.length;
  115. var imgUrl = node.attr.src;
  116. if (imgUrl.indexOf("http") < 0) {
  117. imgUrl = imagedomain + node.attr.src;
  118. }
  119. if (imgUrl[0] == '') {
  120. imgUrl.splice(0, 1);
  121. }
  122. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  123. node.attr.src = imgUrl;
  124. node.from = bindName;
  125. results.images.push(node);
  126. results.imageUrls.push(imgUrl);
  127. }
  128. // 处理font标签样式属性
  129. if (node.tag === 'font') {
  130. var fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
  131. var styleAttrs = {
  132. 'color': 'color',
  133. 'face': 'font-family',
  134. 'size': 'font-size'
  135. };
  136. if (!node.attr.style) node.attr.style = [];
  137. if (!node.styleStr) node.styleStr = '';
  138. for (var key in styleAttrs) {
  139. if (node.attr[key]) {
  140. var value = key === 'size' ? fontSize[node.attr[key]-1] : node.attr[key];
  141. node.attr.style.push(styleAttrs[key]);
  142. node.attr.style.push(value);
  143. node.styleStr += styleAttrs[key] + ': ' + value + ';';
  144. }
  145. }
  146. }
  147. //临时记录source资源
  148. if(node.tag === 'source'){
  149. results.source = node.attr.src;
  150. }
  151. if (unary) {
  152. // if this tag dosen't have end tag
  153. // like <img src="hoge.png"/>
  154. // add to parents
  155. var parent = bufArray[0] || results;
  156. if (parent.nodes === undefined) {
  157. parent.nodes = [];
  158. }
  159. parent.nodes.push(node);
  160. } else {
  161. bufArray.unshift(node);
  162. }
  163. },
  164. end: function (tag) {
  165. //debug(tag);
  166. // merge into parent tag
  167. var node = bufArray.shift();
  168. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  169. //当有缓存source资源时于于video补上src资源
  170. if(node.tag === 'video' && results.source){
  171. node.attr.src = results.source;
  172. delete result.source;
  173. }
  174. if (bufArray.length === 0) {
  175. results.nodes.push(node);
  176. } else {
  177. var parent = bufArray[0];
  178. if (parent.nodes === undefined) {
  179. parent.nodes = [];
  180. }
  181. parent.nodes.push(node);
  182. }
  183. },
  184. chars: function (text) {
  185. //debug(text);
  186. var node = {
  187. node: 'text',
  188. text: text,
  189. textArray:transEmojiStr(text)
  190. };
  191. if (bufArray.length === 0) {
  192. results.nodes.push(node);
  193. } else {
  194. var parent = bufArray[0];
  195. if (parent.nodes === undefined) {
  196. parent.nodes = [];
  197. }
  198. parent.nodes.push(node);
  199. }
  200. },
  201. comment: function (text) {
  202. //debug(text);
  203. // var node = {
  204. // node: 'comment',
  205. // text: text,
  206. // };
  207. // var parent = bufArray[0];
  208. // if (parent.nodes === undefined) {
  209. // parent.nodes = [];
  210. // }
  211. // parent.nodes.push(node);
  212. },
  213. });
  214. return results;
  215. };
  216. function transEmojiStr(str){
  217. // var eReg = new RegExp("["+__reg+' '+"]");
  218. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  219. var emojiObjs = [];
  220. //如果正则表达式为空
  221. if(__emojisReg.length == 0 || !__emojis){
  222. var emojiObj = {}
  223. emojiObj.node = "text";
  224. emojiObj.text = str;
  225. array = [emojiObj];
  226. return array;
  227. }
  228. //这个地方需要调整
  229. str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  230. var eReg = new RegExp("[:]");
  231. var array = str.split(eReg);
  232. for(var i = 0; i < array.length; i++){
  233. var ele = array[i];
  234. var emojiObj = {};
  235. if(__emojis[ele]){
  236. emojiObj.node = "element";
  237. emojiObj.tag = "emoji";
  238. emojiObj.text = __emojis[ele];
  239. emojiObj.baseSrc= __emojisBaseSrc;
  240. }else{
  241. emojiObj.node = "text";
  242. emojiObj.text = ele;
  243. }
  244. emojiObjs.push(emojiObj);
  245. }
  246. return emojiObjs;
  247. }
  248. function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
  249. __emojisReg = reg;
  250. __emojisBaseSrc=baseSrc;
  251. __emojis=emojis;
  252. }
  253. module.exports = {
  254. html2json: html2json,
  255. emojisInit:emojisInit
  256. };