automatic.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * Json Page Automatic Format Via FeHelper
  3. * @author zhaoxianlie
  4. */
  5. // json with bigint supported
  6. Tarp.require('../static/vendor/json-bigint/index');
  7. module.exports = (() => {
  8. "use strict";
  9. let _htmlFragment = [
  10. '<style type="text/css">.mod-contentscript #formattingMsg{position:absolute;top:0;font-size:14px;color:#333;margin:5px;}#formattingMsg .x-loading{width:12px;height:12px;border:1px solid #f00;border-radius:50%;box-shadow:0 0 10px 2px;color:#c00;border-right-color:transparent;border-top-color:transparent;animation:spin-right 1s linear infinite normal;animation-delay:0s;margin:0 5px 0 0;display:inline-block}#formattingMsg .x-loading:before{display:block;width:8px;height:8px;margin:1px;border:2px solid #f00;content:" ";border-radius:50%;border-left-color:transparent;border-bottom-color:transparent}@keyframes spin-right{from{transform:rotate(0deg);opacity:.2}50%{transform:rotate(180deg);opacity:1.0}to{transform:rotate(360deg);opacity:.2}}</style>',
  11. '<div class="mod-json mod-contentscript"><div class="rst-item">',
  12. '<div id="formattingMsg"><span class="x-loading"></span>格式化中...</div>',
  13. '<div id="jfCallbackName_start" class="callback-name"></div>',
  14. '<div id="jfContent"></div>',
  15. '<pre id="jfContent_pre"></pre>',
  16. '<div id="jfCallbackName_end" class="callback-name"></div>',
  17. '</div></div>'
  18. ].join('');
  19. let _loadCss = function () {
  20. let cssUrl = chrome.extension.getURL('json-format/without-ui.css');
  21. $('<link id="_fehelper_fcp_css_" href="' + cssUrl + '" rel="stylesheet" type="text/css" />').appendTo('head');
  22. };
  23. /**
  24. * 从页面提取JSON文本
  25. * @returns {string}
  26. * @private
  27. */
  28. let _getJsonText = function () {
  29. let pre = $('body>pre:eq(0)')[0] || {textContent: ""};
  30. let source = $.trim(pre.textContent);
  31. if (!source) {
  32. source = $.trim(document.body.textContent || '')
  33. }
  34. if (!source) {
  35. return false;
  36. }
  37. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  38. // 如果是合法的json,也只可能有一个text节点
  39. let nodes = document.body.childNodes;
  40. let newSource = '';
  41. for (let i = 0, len = nodes.length; i < len; i++) {
  42. if (nodes[i].nodeType === Node.TEXT_NODE) {
  43. newSource += nodes[i].textContent;
  44. } else if (nodes[i].nodeType === Node.ELEMENT_NODE) {
  45. let tagName = nodes[i].tagName.toLowerCase();
  46. let html = $.trim(nodes[i].textContent);
  47. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  48. if (tagName === 'pre' && html === source) {
  49. } else if ((nodes[i].offsetWidth === 0 || nodes[i].offsetHeight === 0 || !html) && ['script', 'link'].indexOf(tagName) === -1) {
  50. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  51. } else {
  52. return false;
  53. }
  54. } else {
  55. return false;
  56. }
  57. }
  58. return $.trim(newSource || '') || source;
  59. };
  60. /**
  61. * 此方法用于将Unicode码解码为正常字符串
  62. * @param {Object} text
  63. */
  64. let _uniDecode = function (text) {
  65. try{
  66. text = decodeURIComponent(text);
  67. }catch(e){}
  68. text = text.replace(/(\\)?\\u/gi, "%u").replace('%u0025', '%25');
  69. text = unescape(text.toString().replace(/%2B/g, "+"));
  70. let matches = text.match(/(%u00([0-9A-F]{2}))/gi);
  71. if (matches) {
  72. for (let matchid = 0; matchid < matches.length; matchid++) {
  73. let code = matches[matchid].substring(1, 3);
  74. let x = Number("0x" + code);
  75. if (x >= 128) {
  76. text = text.replace(matches[matchid], code);
  77. }
  78. }
  79. }
  80. text = unescape(text.toString().replace(/%2B/g, "+"));
  81. return text;
  82. };
  83. /**
  84. * 获取一个JSON的所有Key数量
  85. * @param json
  86. * @returns {number}
  87. * @private
  88. */
  89. let _getAllKeysCount = function (json) {
  90. let count = 0;
  91. if (typeof json === 'object') {
  92. let keys = Object.keys(json);
  93. count += keys.length;
  94. keys.forEach(key => {
  95. if (json[key] && typeof json[key] === 'object') {
  96. count += _getAllKeysCount(json[key]);
  97. }
  98. });
  99. }
  100. return count;
  101. };
  102. /**
  103. * 执行format操作
  104. * @private
  105. */
  106. let _format = function (options) {
  107. let source = _getJsonText();
  108. if (!source) {
  109. return;
  110. }
  111. if (options && options['AUTO_TEXT_DECODE']) {
  112. source = _uniDecode(source);
  113. }
  114. // JSONP形式下的callback name
  115. let funcName = null;
  116. let jsonObj = null;
  117. let fnTry = null;
  118. let fnCatch = null;
  119. // 下面校验给定字符串是否为一个合法的json
  120. try {
  121. // 再看看是不是jsonp的格式
  122. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
  123. let reTry = /^(try\s*\{\s*)?/g;
  124. let reCatch = /([;\s]*\}\s*catch\s*\(\s*\S+\s*\)\s*\{([\s\S])*\})?[;\s]*$/g;
  125. // 检测是否有try-catch包裹
  126. let sourceReplaced = source.replace(reTry, function () {
  127. fnTry = fnTry ? fnTry : arguments[1];
  128. return '';
  129. }).replace(reCatch, function () {
  130. fnCatch = fnCatch ? fnCatch : arguments[1];
  131. return '';
  132. }).trim();
  133. let matches = reg.exec(sourceReplaced);
  134. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  135. funcName = matches[1];
  136. source = matches[2];
  137. } else {
  138. reg = /^([\{\[])/;
  139. if (!reg.test(source)) {
  140. return;
  141. }
  142. }
  143. // 这里可能会throw exception
  144. jsonObj = JSON.parse(source);
  145. } catch (ex) {
  146. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  147. try {
  148. jsonObj = new Function("return " + source)();
  149. } catch (exx) {
  150. try {
  151. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  152. jsonObj = new Function("return '" + source + "'")();
  153. if (typeof jsonObj === 'string') {
  154. // 最后给你一次机会,是个字符串,老夫给你再转一次
  155. jsonObj = new Function("return " + jsonObj)();
  156. }
  157. } catch (exxx) {
  158. return;
  159. }
  160. }
  161. }
  162. // 是json格式,可以进行JSON自动格式化
  163. if (jsonObj != null && typeof jsonObj === "object") {
  164. try {
  165. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  166. source = JSON.stringify(jsonObj);
  167. } catch (ex) {
  168. // 通过JSON反解不出来的,一定有问题
  169. return;
  170. }
  171. // JSON的所有key不能超过预设的值,比如 10000 个,要不然自动格式化会比较卡
  172. if (options && options['MAX_JSON_KEYS_NUMBER']) {
  173. let keysCount = _getAllKeysCount(jsonObj);
  174. if (keysCount > options['MAX_JSON_KEYS_NUMBER']) {
  175. let msg = '当前JSON共 <b style="color:red">' + keysCount + '</b> 个Key,大于预设值' + options['MAX_JSON_KEYS_NUMBER'] + ',已取消自动格式化;可到FeHelper设置页调整此配置!';
  176. return toast(msg);
  177. }
  178. }
  179. _loadCss();
  180. $('body').html(_htmlFragment);
  181. // 格式化
  182. Tarp.require('../json-format/format-lib').format(source);
  183. // 如果是JSONP格式的,需要把方法名也显示出来
  184. if (funcName != null) {
  185. if (fnTry && fnCatch) {
  186. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  187. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  188. } else {
  189. $('#jfCallbackName_start').html(funcName + '(');
  190. $('#jfCallbackName_end').html(')');
  191. }
  192. }
  193. }
  194. };
  195. return {
  196. format: _format
  197. };
  198. })();