content-script.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /**
  2. * Json Page Automatic Format Via FeHelper
  3. * @author zhaoxianlie
  4. */
  5. window.JsonAutoFormat = (() => {
  6. // 留100ms时间给静态文件加载,当然,这个代码只是留给未开发过程中用的
  7. let pleaseLetJsLoaded = 0;
  8. let __importScript = (filename) => {
  9. pleaseLetJsLoaded = 100;
  10. let url = filename;
  11. if (location.protocol === 'chrome-extension:' || chrome.runtime && chrome.runtime.getURL) {
  12. url = chrome.runtime.getURL('json-format/' + filename);
  13. }
  14. fetch(url).then(resp => resp.text()).then(jsText => {
  15. if(window.evalCore && window.evalCore.getEvalInstance){
  16. return window.evalCore.getEvalInstance(window)(jsText);
  17. }
  18. let el = document.createElement('script');
  19. el.textContent = jsText;
  20. document.head.appendChild(el);
  21. });
  22. };
  23. __importScript('json-bigint.js');
  24. __importScript('format-lib.js');
  25. __importScript('json-abc.js');
  26. __importScript('json-decode.js');
  27. const JSON_SORT_TYPE_KEY = 'json_sort_type_key';
  28. // 本地永久存储的key
  29. const STORAGE_KEYS = {
  30. // 总是开启JSON自动格式化功能
  31. JSON_PAGE_FORMAT: 'JSON_PAGE_FORMAT',
  32. // 总是显示顶部工具栏
  33. JSON_TOOL_BAR_ALWAYS_SHOW: 'JSON_TOOL_BAR_ALWAYS_SHOW',
  34. // 启用底部状态栏
  35. STATUS_BAR_ALWAYS_SHOW: 'STATUS_BAR_ALWAYS_SHOW',
  36. // 自动进行URL、Unicode解码
  37. AUTO_TEXT_DECODE: 'AUTO_TEXT_DECODE',
  38. // 修正乱码
  39. FIX_ERROR_ENCODING: 'FIX_ERROR_ENCODING',
  40. // 启用JSON key排序功能
  41. ENABLE_JSON_KEY_SORT: 'ENABLE_JSON_KEY_SORT',
  42. // 保留键值双引号
  43. KEEP_KEY_VALUE_DBL_QUOTE: 'KEEP_KEY_VALUE_DBL_QUOTE',
  44. // 最大json key数量
  45. MAX_JSON_KEYS_NUMBER: 'MAX_JSON_KEYS_NUMBER',
  46. // 自定义皮肤
  47. JSON_FORMAT_THEME: 'JSON_FORMAT_THEME'
  48. };
  49. // 皮肤定义
  50. const SKIN_THEME = {
  51. '0': 'theme-default',
  52. '1': 'theme-simple',
  53. '2': 'theme-light',
  54. '3': 'theme-dark',
  55. '4': 'theme-vscode',
  56. '5': 'theme-github',
  57. '6': 'theme-vegetarian'
  58. };
  59. // JSONP形式下的callback name
  60. let funcName = null;
  61. let jsonObj = null;
  62. let fnTry = null;
  63. let fnCatch = null;
  64. // 格式化的配置
  65. let formatOptions = {
  66. JSON_FORMAT_THEME: 0,
  67. sortType: 0,
  68. autoDecode: false,
  69. originalSource: ''
  70. };
  71. // 获取JSON格式化的配置信息
  72. let _getAllOptions = (success) => {
  73. chrome.runtime.sendMessage({
  74. type: 'fh-dynamic-any-thing',
  75. thing:'request-jsonformat-options',
  76. params: STORAGE_KEYS
  77. }).then(result => success(result));
  78. };
  79. let _getHtmlFragment = () => {
  80. return [
  81. '<div id="jfToolbar" class="x-toolbar" style="display:none">' +
  82. ' <a href="https://www.baidufe.com/fehelper/feedback.html" target="_blank" class="x-a-title">' +
  83. ' <img src="' + chrome.runtime.getURL('static/img/fe-16.png') + '" alt="fehelper"/> FeHelper</a>' +
  84. ' <span class="x-b-title"></span>' +
  85. ' <span class="x-sort">' +
  86. ' <span class="x-split">|</span>' +
  87. ' <span class="x-stitle">排序:</span>' +
  88. ' <label for="sort_null">默认</label><input type="radio" name="jsonsort" id="sort_null" value="0" checked>' +
  89. ' <label for="sort_asc">升序</label><input type="radio" name="jsonsort" id="sort_asc" value="1">' +
  90. ' <label for="sort_desc">降序</label><input type="radio" name="jsonsort" id="sort_desc" value="-1">' +
  91. ' </span>' +
  92. ' <span class="x-fix-encoding"><span class="x-split">|</span><button class="xjf-btn" id="jsonGetCorrectCnt">乱码修正</button></span>' +
  93. ' <span id="optionBar"></span>' +
  94. ' <span class="fe-feedback">' +
  95. ' <span class="x-settings"><svg aria-hidden="true" height="16" version="1.1" viewBox="0 0 14 16" width="14">' +
  96. ' <path fill-rule="evenodd" d="M14 8.77v-1.6l-1.94-.64-.45-1.09.88-1.84-1.13-1.13-1.81.91-1.09-.45-.69-1.92h-1.6l-.63 1.94-1.11.45-1.84-.88-1.13 1.13.91 1.81-.45 1.09L0 7.23v1.59l1.94.64.45 1.09-.88 1.84 1.13 1.13 1.81-.91 1.09.45.69 1.92h1.59l.63-1.94 1.11-.45 1.84.88 1.13-1.13-.92-1.81.47-1.09L14 8.75v.02zM7 11c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"></path>' +
  97. ' </svg>高级定制</span>' +
  98. ' <a id="toggleBtn" title="展开或收起工具栏">隐藏&gt;&gt;</a>' +
  99. ' </span>' +
  100. '</div>',
  101. '<div id="formattingMsg"><span class="x-loading"></span>格式化中...</div>',
  102. '<div class="mod-json mod-contentscript"><div class="rst-item">',
  103. '<div id="jfCallbackName_start" class="callback-name"></div>',
  104. '<div id="jfContent"></div>',
  105. '<pre id="jfContent_pre"></pre>',
  106. '<div id="jfCallbackName_end" class="callback-name"></div>',
  107. '</div></div>'
  108. ].join('')
  109. };
  110. let _createSettingPanel = () => {
  111. let html = `<div id="jfSettingPanel" class="mod-setting-panel">
  112. <h4>基本配置项</h4>
  113. <form action="#">
  114. <ul>
  115. <li><label><input type="checkbox" name="alwaysOn" value="1">总是开启JSON自动格式化功能</label></li>
  116. <li><label><input type="checkbox" name="alwaysShowToolbar" value="1">总是显示顶部工具栏</label></li>
  117. <li><label><input type="checkbox" name="alwaysShowStatusbar" value="1">启用状态栏(包含复制/下载/删除)</label></li>
  118. <li><label><input type="checkbox" name="autoDecode" value="1">自动进行URL、Unicode解码</label></li>
  119. <li><label><input type="checkbox" name="errorEncoding" value="1">乱码修正(需手动操作,一键修正)</label></li>
  120. <li><label><input type="checkbox" name="enableSort" value="1">启用JSON键名排序功能</label></li>
  121. <li><label><input type="checkbox" name="keepQuote" value="1">格式化后保留键值对的双引号</label></li>
  122. <li><label><input type="text" name="maxlength" value="10000">最大支持的JSON Key数量</label></li>
  123. </ul>
  124. <h4>自定义皮肤</h4>
  125. <ul>
  126. <li><label><input type="radio" name="skinId" value="0">默认模式(简约风格)</label></li>
  127. <li><label><input type="radio" name="skinId" value="1">极简模式(纯源码)</label></li>
  128. <li><label><input type="radio" name="skinId" value="2">清爽模式(明亮、跳跃)</label></li>
  129. <li><label><input type="radio" name="skinId" value="3">暗黑模式(安静、忧郁)</label></li>
  130. <li><label><input type="radio" name="skinId" value="4">vscode模式(醒目、专注)</label></li>
  131. <li><label><input type="radio" name="skinId" value="5">github模式(纵享丝滑)</label></li>
  132. <li><label><input type="radio" name="skinId" value="6">素人模式(清心寡欲)</label></li>
  133. </ul>
  134. <div class="btns">
  135. <input type="submit" class="xjf-btn" name="submit" value="确定">
  136. <input type="reset" class="xjf-btn" name="reset" value="取消">
  137. </div>
  138. </form>
  139. </div>`;
  140. let sPanel = $('#jfSettingPanel');
  141. if (!sPanel.length) {
  142. sPanel = $(html).appendTo('#jfToolbar');
  143. // 表单提交时,保存数据
  144. sPanel.find('input[type="submit"]').on('click', function (e) {
  145. e.preventDefault();
  146. e.stopPropagation();
  147. let formData = {};
  148. formData.JSON_PAGE_FORMAT = sPanel.find('input[name="alwaysOn"]').prop('checked');
  149. formData.JSON_TOOL_BAR_ALWAYS_SHOW = sPanel.find('input[name="alwaysShowToolbar"]').prop('checked');
  150. formData.STATUS_BAR_ALWAYS_SHOW = sPanel.find('input[name="alwaysShowStatusbar"]').prop('checked');
  151. formData.AUTO_TEXT_DECODE = sPanel.find('input[name="autoDecode"]').prop('checked');
  152. formData.FIX_ERROR_ENCODING = sPanel.find('input[name="errorEncoding"]').prop('checked');
  153. formData.ENABLE_JSON_KEY_SORT = sPanel.find('input[name="enableSort"]').prop('checked');
  154. formData.KEEP_KEY_VALUE_DBL_QUOTE = sPanel.find('input[name="keepQuote"]').prop('checked');
  155. formData.MAX_JSON_KEYS_NUMBER = sPanel.find('input[name="maxlength"]').val();
  156. formData.JSON_FORMAT_THEME = sPanel.find('input[name="skinId"]:checked').val();
  157. chrome.runtime.sendMessage({
  158. type: 'fh-dynamic-any-thing',
  159. thing: 'save-jsonformat-options',
  160. params: formData
  161. }, result => sPanel.hide());
  162. });
  163. sPanel.find('input[name="alwaysShowToolbar"]').on('click', function (e) {
  164. $('.fe-feedback #toggleBtn').trigger('click');
  165. });
  166. sPanel.find('input[name="errorEncoding"]').on('click', function (e) {
  167. let el = $('#jfToolbar').find('.x-fix-encoding');
  168. $(this).prop('checked') ? el.show() : el.hide();
  169. });
  170. sPanel.find('input[name="enableSort"]').on('click', function (e) {
  171. let el = $('#jfToolbar').find('.x-sort');
  172. $(this).prop('checked') ? el.show() : el.hide();
  173. });
  174. sPanel.find('input[type="reset"]').on('click', (e) => sPanel.hide());
  175. sPanel.find('input[name="skinId"]').on('click', function (e) {
  176. formatOptions.JSON_FORMAT_THEME = this.value;
  177. _didFormat();
  178. });
  179. sPanel.find('input[name="alwaysShowStatusbar"]').on('click', function (e) {
  180. formatOptions.STATUS_BAR_ALWAYS_SHOW = $(this).prop('checked');
  181. let elBody = $('body');
  182. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  183. elBody.removeClass('hide-status-bar');
  184. } else {
  185. elBody.addClass('hide-status-bar');
  186. }
  187. });
  188. sPanel.find('input[name="keepQuote"]').on('click', function (e) {
  189. formatOptions.KEEP_KEY_VALUE_DBL_QUOTE = $(this).prop('checked');
  190. let elBody = $('body');
  191. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  192. elBody.removeClass('remove-quote');
  193. } else {
  194. elBody.addClass('remove-quote');
  195. }
  196. });
  197. } else if (sPanel[0].offsetHeight) {
  198. return sPanel.hide();
  199. } else {
  200. sPanel.show();
  201. }
  202. _getAllOptions(result => {
  203. result.JSON_PAGE_FORMAT && sPanel.find('input[name="alwaysOn"]').prop('checked', true);
  204. result.JSON_TOOL_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowToolbar"]').prop('checked', true);
  205. result.STATUS_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowStatusbar"]').prop('checked', true);
  206. result.AUTO_TEXT_DECODE && sPanel.find('input[name="autoDecode"]').prop('checked', true);
  207. result.FIX_ERROR_ENCODING && sPanel.find('input[name="errorEncoding"]').prop('checked', true);
  208. result.ENABLE_JSON_KEY_SORT && sPanel.find('input[name="enableSort"]').prop('checked', true);
  209. result.KEEP_KEY_VALUE_DBL_QUOTE && sPanel.find('input[name="keepQuote"]').prop('checked', true);
  210. sPanel.find('input[name="maxlength"]').attr('value', result.MAX_JSON_KEYS_NUMBER || 10000);
  211. sPanel.find(`input[name="skinId"][value="${result.JSON_FORMAT_THEME || 0}"]`).attr('checked', true);
  212. });
  213. };
  214. // 检测当前页面的CSP,防止出现这种情况:
  215. // DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
  216. let _checkContentSecurityPolicy = () => {
  217. try {
  218. localStorage.getItem(1);
  219. } catch (e) {
  220. return false;
  221. }
  222. return true;
  223. };
  224. let _initToolbar = () => {
  225. let cspSafe = _checkContentSecurityPolicy();
  226. if (cspSafe) {
  227. // =============================排序:获取上次记录的排序方式
  228. if (formatOptions.ENABLE_JSON_KEY_SORT) {
  229. formatOptions.sortType = parseInt(localStorage.getItem(JSON_SORT_TYPE_KEY) || 0);
  230. // 排序选项初始化
  231. $('[name=jsonsort][value=' + formatOptions.sortType + ']').attr('checked', 1);
  232. } else {
  233. formatOptions.sortType = 0;
  234. $('#jfToolbar .x-sort').hide();
  235. }
  236. // =============================事件初始化
  237. $('[name=jsonsort]').click(function (e) {
  238. let sortType = parseInt(this.value);
  239. if (sortType !== formatOptions.sortType) {
  240. formatOptions.sortType = sortType;
  241. _didFormat();
  242. }
  243. localStorage.setItem(JSON_SORT_TYPE_KEY, sortType);
  244. });
  245. } else {
  246. $('#jfToolbar .x-sort').hide();
  247. }
  248. // =============================乱码修正
  249. if (!formatOptions.FIX_ERROR_ENCODING) {
  250. $('#jfToolbar .x-fix-encoding').hide();
  251. }
  252. // =============================工具栏的显示与隐藏控制
  253. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  254. let tgBtn = $('.fe-feedback #toggleBtn');
  255. if (formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW) {
  256. toolBarClassList.remove('t-collapse');
  257. tgBtn.html('隐藏&gt;&gt;');
  258. } else {
  259. toolBarClassList.add('t-collapse');
  260. tgBtn.html('&lt;&lt;');
  261. }
  262. tgBtn.click(function (e) {
  263. e.preventDefault();
  264. e.stopPropagation();
  265. chrome.runtime.sendMessage({
  266. type: 'fh-dynamic-any-thing',
  267. thing: 'toggle-jsonformat-options'
  268. }).then(show => {
  269. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  270. if (show) {
  271. toolBarClassList.remove('t-collapse');
  272. tgBtn.html('隐藏&gt;&gt;');
  273. } else {
  274. toolBarClassList.add('t-collapse');
  275. tgBtn.html('&lt;&lt;');
  276. }
  277. $('#jfToolbar input[name="alwaysShowToolbar"]').prop('checked', show);
  278. });
  279. });
  280. $('.fe-feedback .x-settings').click(e => _createSettingPanel());
  281. $('#jsonGetCorrectCnt').click(e => _getCorrectContent());
  282. };
  283. let _didFormat = function () {
  284. let source = formatOptions.originalSource;
  285. if (formatOptions.sortType !== 0) {
  286. let jsonObj = JsonABC.sortObj(JSON.parse(formatOptions.originalSource), parseInt(formatOptions.sortType), true);
  287. source = JSON.stringify(jsonObj);
  288. }
  289. let elBody = $('body');
  290. let theme = SKIN_THEME[formatOptions.JSON_FORMAT_THEME || 0];
  291. Object.values(SKIN_THEME).forEach(th => elBody.removeClass(th));
  292. elBody.addClass(theme);
  293. // 控制引号
  294. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  295. elBody.removeClass('remove-quote');
  296. } else {
  297. elBody.addClass('remove-quote');
  298. }
  299. // 控制底部状态栏
  300. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  301. elBody.removeClass('hide-status-bar');
  302. } else {
  303. elBody.addClass('hide-status-bar');
  304. }
  305. if (formatOptions.autoDecode) {
  306. (async () => {
  307. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  308. source = JsonEnDecode.uniDecode(txt);
  309. // 格式化
  310. try {
  311. Formatter.format(source, theme);
  312. } catch (e) {
  313. Formatter.formatSync(source, theme)
  314. }
  315. $('#jfToolbar').fadeIn(500);
  316. })();
  317. } else {
  318. // 格式化
  319. try {
  320. Formatter.format(source, theme);
  321. } catch (e) {
  322. Formatter.formatSync(source, theme)
  323. }
  324. $('#jfToolbar').fadeIn(500);
  325. }
  326. // 如果是JSONP格式的,需要把方法名也显示出来
  327. if (funcName != null) {
  328. if (fnTry && fnCatch) {
  329. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  330. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  331. } else {
  332. $('#jfCallbackName_start').html(funcName + '(');
  333. $('#jfCallbackName_end').html(')');
  334. }
  335. }
  336. };
  337. let _getCorrectContent = function () {
  338. fetch(location.href).then(res => res.text()).then(text => {
  339. formatOptions.originalSource = text;
  340. _didFormat();
  341. });
  342. };
  343. /**
  344. * 从页面提取JSON文本
  345. * @returns {string}
  346. * @private
  347. */
  348. let _getJsonText = function () {
  349. let pre = document.querySelectorAll('body>pre')[0] || {textContent: ""};
  350. let source = pre.textContent.trim();
  351. if (!source) {
  352. source = (document.body.textContent || '').trim()
  353. }
  354. // 如果是js内容,则不进行json格式化
  355. let isJs = /\.js$/.test(new URL(location.href).pathname);
  356. isJs = isJs && document.contentType === 'application/javascript';
  357. if (isJs) {
  358. source = '';
  359. }
  360. if (!source) {
  361. return false;
  362. }
  363. // 1、如果body的内容还包含HTML标签,肯定不是合法的json了
  364. // 2、如果是合法的json,也只可能有一个text节点
  365. // 3、但是要兼容一下其他插件对页面的破坏情况
  366. // 4、对于content-type是application/json的页面可以做宽松处理
  367. let nodes = document.body.childNodes;
  368. let jsonText = '';
  369. let isJsonContentType = document.contentType === 'application/json';
  370. for (let i = 0, len = nodes.length; i < len; i++) {
  371. let elm = nodes[i];
  372. if (elm.nodeType === Node.TEXT_NODE) {
  373. jsonText += (elm.textContent || '').trim();
  374. } else if (isJsonContentType) {
  375. if ((elm.offsetHeight + elm.offsetWidth !== 0) && elm.textContent.length > jsonText.length) {
  376. jsonText = elm.textContent;
  377. }
  378. } else {
  379. if (nodes[i].nodeType === Node.ELEMENT_NODE) {
  380. let tagName = elm.tagName.toLowerCase();
  381. let text = (elm.textContent || '').trim();
  382. // 如果包含了script和link标签,需要看标签的src和href属性值,如果不是chrome-extensions注入的,也要跳出
  383. if (['script', 'link'].includes(tagName)) {
  384. let url = elm.getAttribute('src') || elm.getAttribute('href');
  385. if (!!url && !/^chrome\-extension:\/\//.test(url)) {
  386. return false;
  387. }
  388. }
  389. // 如果不是pre标签,并且还不是隐藏节点,且内容不为空,也要跳出
  390. else if (tagName !== 'pre' && (elm.offsetWidth + elm.offsetHeight !== 0 && !!text)) {
  391. return false;
  392. }
  393. // 如果是pre标签,但当前节点内容与最初body.textContent提取值不一致,都跳出
  394. else if (tagName === 'pre' && text !== source) {
  395. return false;
  396. }
  397. } else {
  398. return false;
  399. }
  400. }
  401. }
  402. return (jsonText || '').trim() || source;
  403. };
  404. /**
  405. * 获取一个JSON的所有Key数量
  406. * @param json
  407. * @returns {number}
  408. * @private
  409. */
  410. let _getAllKeysCount = function (json) {
  411. let count = 0;
  412. if (typeof json === 'object') {
  413. let keys = Object.keys(json);
  414. count += keys.length;
  415. keys.forEach(key => {
  416. if (json[key] && typeof json[key] === 'object') {
  417. count += _getAllKeysCount(json[key]);
  418. }
  419. });
  420. }
  421. return count;
  422. };
  423. // 用新的options来覆盖默认options
  424. let _extendsOptions = options => {
  425. options = options || {};
  426. Object.keys(options).forEach(opt => formatOptions[opt] = options[opt]);
  427. };
  428. /**
  429. * 执行format操作
  430. * @private
  431. */
  432. let _format = function (options) {
  433. let source = _getJsonText();
  434. if (!source) {
  435. return;
  436. }
  437. _extendsOptions(options);
  438. // 下面校验给定字符串是否为一个合法的json
  439. try {
  440. // 再看看是不是jsonp的格式
  441. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
  442. let reTry = /^(try\s*\{\s*)?/g;
  443. let reCatch = /([;\s]*\}\s*catch\s*\(\s*\S+\s*\)\s*\{([\s\S])*\})?[;\s]*$/g;
  444. // 检测是否有try-catch包裹
  445. let sourceReplaced = source.replace(reTry, function () {
  446. fnTry = fnTry ? fnTry : arguments[1];
  447. return '';
  448. }).replace(reCatch, function () {
  449. fnCatch = fnCatch ? fnCatch : arguments[1];
  450. return '';
  451. }).trim();
  452. let matches = reg.exec(sourceReplaced);
  453. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  454. funcName = matches[1];
  455. source = matches[2];
  456. } else {
  457. reg = /^([\{\[])/;
  458. if (!reg.test(source)) {
  459. return;
  460. }
  461. }
  462. // 这里可能会throw exception
  463. jsonObj = JSON.parse(source);
  464. } catch (ex) {
  465. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  466. try {
  467. jsonObj = new Function("return " + source)();
  468. } catch (exx) {
  469. try {
  470. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  471. jsonObj = new Function("return '" + source + "'")();
  472. if (typeof jsonObj === 'string') {
  473. try {
  474. // 确保bigint不会失真
  475. jsonObj = JSON.parse(jsonObj);
  476. } catch (ie) {
  477. // 最后给你一次机会,是个字符串,老夫给你再转一次
  478. jsonObj = new Function("return " + jsonObj)();
  479. }
  480. }
  481. } catch (exxx) {
  482. return;
  483. }
  484. }
  485. }
  486. // 是json格式,可以进行JSON自动格式化
  487. if (jsonObj != null && typeof jsonObj === "object") {
  488. try {
  489. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  490. source = JSON.stringify(jsonObj);
  491. } catch (ex) {
  492. // 通过JSON反解不出来的,一定有问题
  493. return;
  494. }
  495. // JSON的所有key不能超过预设的值,比如 10000 个,要不然自动格式化会比较卡
  496. if (formatOptions['MAX_JSON_KEYS_NUMBER']) {
  497. let keysCount = _getAllKeysCount(jsonObj);
  498. if (keysCount > formatOptions['MAX_JSON_KEYS_NUMBER']) {
  499. let msg = '当前JSON共 <b style="color:red">' + keysCount + '</b> 个Key,大于预设值' + formatOptions['MAX_JSON_KEYS_NUMBER'] + ',已取消自动格式化;可到FeHelper设置页调整此配置!';
  500. return toast(msg);
  501. }
  502. }
  503. $('body').prepend(_getHtmlFragment());
  504. let preLength = $('body>pre').remove().length;
  505. if (!preLength) {
  506. Array.prototype.slice.call(document.body.childNodes).forEach(node => {
  507. (node.nodeType === Node.TEXT_NODE) && node.remove();
  508. });
  509. }
  510. formatOptions.originalSource = source;
  511. _initToolbar();
  512. _didFormat();
  513. }
  514. };
  515. return {
  516. format: () => _getAllOptions(result => {
  517. if(result.JSON_PAGE_FORMAT) {
  518. let intervalId = setInterval(() => {
  519. if(typeof Formatter !== 'undefined') {
  520. clearInterval(intervalId);
  521. _format(result);
  522. }
  523. },pleaseLetJsLoaded);
  524. }
  525. })
  526. };
  527. })();
  528. if(location.protocol !== 'chorme-extension:') {
  529. window.JsonAutoFormat.format();
  530. }