automatic.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /**
  2. * Json Page Automatic Format Via FeHelper
  3. * @author zhaoxianlie
  4. */
  5. module.exports = (() => {
  6. "use strict";
  7. let _htmlFragment = [
  8. '<div class="mod-json mod-contentscript"><div class="rst-item">',
  9. '<div id="formattingMsg">',
  10. '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">',
  11. '<path d="M 150,0 a 150,150 0 0,1 106.066,256.066 l -35.355,-35.355 a -100,-100 0 0,0 -70.711,-170.711 z" fill="#3d7fe6"></path>',
  12. '</svg>加载中...',
  13. '</div>',
  14. '<div id="jfCallbackName_start" class="callback-name"></div>',
  15. '<div id="jfContent"></div>',
  16. '<pre id="jfContent_pre"></pre>',
  17. '<div id="jfCallbackName_end" class="callback-name"></div>',
  18. '</div></div>'
  19. ].join('');
  20. let _loadCss = function () {
  21. let cssUrl = chrome.extension.getURL('json-format/without-ui.css');
  22. jQuery('<link id="_fehelper_fcp_css_" href="' + cssUrl + '" rel="stylesheet" type="text/css" />').appendTo('head');
  23. };
  24. /**
  25. * 从页面提取JSON文本
  26. * @returns {string}
  27. * @private
  28. */
  29. let _getJsonText = function () {
  30. let pre = $('body>pre:eq(0)')[0] || {textContent: ""};
  31. let source = $.trim(pre.textContent);
  32. if (!source) {
  33. source = $.trim(document.body.textContent || '')
  34. }
  35. if (!source) {
  36. return false;
  37. }
  38. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  39. // 如果是合法的json,也只可能有一个text节点
  40. let nodes = document.body.childNodes;
  41. let newSource = '';
  42. for (let i = 0, len = nodes.length; i < len; i++) {
  43. if (nodes[i].nodeType === Node.TEXT_NODE) {
  44. newSource += nodes[i].textContent;
  45. } else if (nodes[i].nodeType === Node.ELEMENT_NODE) {
  46. let tagName = nodes[i].tagName.toLowerCase();
  47. let html = $.trim(nodes[i].textContent);
  48. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  49. if (tagName === 'pre' && html === source) {
  50. } else if ((nodes[i].offsetWidth === 0 || nodes[i].offsetHeight === 0 || !html) && ['script', 'link'].indexOf(tagName) === -1) {
  51. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  52. } else {
  53. return false;
  54. }
  55. } else {
  56. return false;
  57. }
  58. }
  59. return $.trim(newSource || '') || source;
  60. };
  61. /**
  62. * 此方法用于将Unicode码解码为正常字符串
  63. * @param {Object} text
  64. */
  65. let _uniDecode = function (text) {
  66. text = text.replace(/\\/g, "%").replace('%U', '%u').replace('%u0025', '%25');
  67. text = unescape(text.toString().replace(/%2B/g, "+"));
  68. let matches = text.match(/(%u00([0-9A-F]{2}))/gi);
  69. if (matches) {
  70. for (let matchid = 0; matchid < matches.length; matchid++) {
  71. let code = matches[matchid].substring(1, 3);
  72. let x = Number("0x" + code);
  73. if (x >= 128) {
  74. text = text.replace(matches[matchid], code);
  75. }
  76. }
  77. }
  78. text = unescape(text.toString().replace(/%2B/g, "+"));
  79. return text;
  80. };
  81. /**
  82. * 执行format操作
  83. * @private
  84. */
  85. let _format = function () {
  86. let source = _getJsonText();
  87. if (!source) {
  88. return;
  89. }
  90. // JSONP形式下的callback name
  91. let funcName = null;
  92. // json对象
  93. let jsonObj = null;
  94. let newSource = source;
  95. let fnTry = null;
  96. let fnCatch = null;
  97. // 下面校验给定字符串是否为一个合法的json
  98. try {
  99. // 再看看是不是jsonp的格式
  100. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
  101. let reTry = /^(try\s*\{\s*)?/g;
  102. let reCatch = /(\}\s*catch\s*\(\s*\S+\s*\)\s*\{([\s\S])*\})?$/g;
  103. // 检测是否有try-catch包裹
  104. let sourceReplaced = source.replace(reTry, function () {
  105. fnTry = fnTry ? fnTry : arguments[1];
  106. return '';
  107. }).replace(reCatch, function () {
  108. fnCatch = fnCatch ? fnCatch : arguments[1];
  109. return '';
  110. }).trim();
  111. let matches = reg.exec(sourceReplaced);
  112. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  113. funcName = matches[1];
  114. newSource = matches[2];
  115. jsonObj = new Function("return " + newSource)();
  116. } else {
  117. reg = /^([\{\[])/;
  118. if (!reg.test(source)) {
  119. return;
  120. }
  121. }
  122. // 强化验证
  123. if (jsonObj == null || typeof jsonObj !== 'object') {
  124. jsonObj = new Function("return " + source)();
  125. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  126. if (typeof jsonObj === "string") {
  127. // 再来一次
  128. jsonObj = new Function("return " + jsonObj)();
  129. }
  130. }
  131. } catch (ex) {
  132. return;
  133. }
  134. // 是json格式,可以进行JSON自动格式化
  135. if (jsonObj != null && typeof jsonObj === "object") {
  136. try {
  137. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  138. let jsonStr = JSON.stringify(jsonObj);
  139. // 如果newSource的长度比原source长度短很多的话,猜测应该是格式化错了,需要撤销操作
  140. // 这里一定要unicode decode一下,要不然会出现误判
  141. let len1 = jsonStr.replace(/'|"|\s/g, '').length;
  142. let len2 = (_uniDecode(newSource)).replace(/'|"|\s/g, '').length;
  143. // 误差不允许超过20%
  144. if (Math.abs(len1 - len2) / ((len1 + len2) / 2) > 0.2) {
  145. return;
  146. }
  147. newSource = jsonStr;
  148. } catch (ex) {
  149. // 通过JSON反解不出来的,一定有问题
  150. return;
  151. }
  152. $('body').html(_htmlFragment);
  153. _loadCss();
  154. // 异步加载模式
  155. Tarp.require('../json-format/format-lib', true).then(Json => {
  156. Json.format(newSource);
  157. // 如果是JSONP格式的,需要把方法名也显示出来
  158. if (funcName != null) {
  159. if (fnTry && fnCatch) {
  160. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  161. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  162. } else {
  163. $('#jfCallbackName_start').html(funcName + '(');
  164. $('#jfCallbackName_end').html(')');
  165. }
  166. }
  167. });
  168. }
  169. };
  170. return {
  171. format: _format
  172. };
  173. })();