content-script.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. let cssInjected = false;
  60. // JSONP形式下的callback name
  61. let funcName = 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. }, result => success(result));
  78. };
  79. let _getHtmlFragment = () => {
  80. // 判断当前地区是否在美国
  81. const isInUSA = () => {
  82. // 通过时区判断是否在美国
  83. const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  84. const isUSTimeZone = /^America\/(New_York|Chicago|Denver|Los_Angeles|Anchorage|Honolulu)/.test(timeZone);
  85. // 通过语言判断
  86. const language = navigator.language || navigator.userLanguage;
  87. const isUSLanguage = language.toLowerCase().indexOf('en-us') > -1;
  88. // 如果时区和语言都符合美国特征,则认为在美国
  89. return (isUSTimeZone && isUSLanguage);
  90. };
  91. return [
  92. '<div id="jfToolbar" class="x-toolbar" style="display:none">' +
  93. ' <a href="https://www.baidufe.com/fehelper/index.html" target="_blank" class="x-a-title">' +
  94. ' <img src="' + chrome.runtime.getURL('static/img/fe-16.png') + '" alt="fehelper"/> FeHelper</a>' +
  95. ' <span class="x-b-title"></span>' +
  96. ' <span class="x-sort">' +
  97. ' <span class="x-split">|</span>' +
  98. ' <span class="x-stitle">排序:</span>' +
  99. ' <label for="sort_null">默认</label><input type="radio" name="jsonsort" id="sort_null" value="0" checked>' +
  100. ' <label for="sort_asc">升序</label><input type="radio" name="jsonsort" id="sort_asc" value="1">' +
  101. ' <label for="sort_desc">降序</label><input type="radio" name="jsonsort" id="sort_desc" value="-1">' +
  102. ' </span>' +
  103. ' <span class="x-fix-encoding"><span class="x-split">|</span><button class="xjf-btn" id="jsonGetCorrectCnt">乱码修正</button></span>' +
  104. ' <span id="optionBar"></span>' +
  105. ' <span class="x-donate-link' + (isInUSA() ? ' x-donate-link-us' : '') + '"><a href="#" id="donateLink"><i class="nav-icon">❤</i>打赏鼓励</a></span>' +
  106. ' <span class="fe-feedback">' +
  107. ' <span class="x-settings"><svg aria-hidden="true" height="16" version="1.1" viewBox="0 0 14 16" width="14">' +
  108. ' <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>' +
  109. ' </svg>高级定制</span>' +
  110. ' <a class="x-other-tools' + (isInUSA() ? ' x-other-tools-us' : '') + '" style="cursor:pointer"><i class="icon-plus-circle">+</i>探索更多实用工具 <span class="tool-market-badge">工具市场</span></a>' +
  111. ' <a id="toggleBtn" title="展开或收起工具栏">隐藏&gt;&gt;</a>' +
  112. ' </span>' +
  113. '</div>',
  114. '<div id="formattingMsg"><span class="x-loading"></span>格式化中...</div>',
  115. '<div class="mod-json mod-contentscript"><div class="rst-item">',
  116. '<div id="jfCallbackName_start" class="callback-name"></div>',
  117. '<div id="jfContent"></div>',
  118. '<pre id="jfContent_pre"></pre>',
  119. '<div id="jfCallbackName_end" class="callback-name"></div>',
  120. '</div></div>'
  121. ].join('')
  122. };
  123. let _createSettingPanel = () => {
  124. let html = `<div id="jfSettingPanel" class="mod-setting-panel">
  125. <h4>基本配置项</h4>
  126. <form action="#">
  127. <ul>
  128. <li><label><input type="checkbox" name="alwaysOn" value="1">总是开启JSON自动格式化功能</label></li>
  129. <li><label><input type="checkbox" name="alwaysShowToolbar" value="1">总是显示顶部工具栏</label></li>
  130. <li><label><input type="checkbox" name="alwaysShowStatusbar" value="1">启用状态栏(包含复制/下载/删除)</label></li>
  131. <li><label><input type="checkbox" name="autoDecode" value="1">自动进行URL、Unicode解码</label></li>
  132. <li><label><input type="checkbox" name="errorEncoding" value="1">乱码修正(需手动操作,一键修正)</label></li>
  133. <li><label><input type="checkbox" name="enableSort" value="1">启用JSON键名排序功能</label></li>
  134. <li><label><input type="checkbox" name="keepQuote" value="1">格式化后保留键值对的双引号</label></li>
  135. <li><label><input type="text" name="maxlength" value="10000">最大支持的JSON Key数量</label></li>
  136. </ul>
  137. <h4>自定义皮肤</h4>
  138. <ul>
  139. <li><label><input type="radio" name="skinId" value="0">默认模式(简约风格)</label></li>
  140. <li><label><input type="radio" name="skinId" value="1">极简模式(纯源码)</label></li>
  141. <li><label><input type="radio" name="skinId" value="2">清爽模式(明亮、跳跃)</label></li>
  142. <li><label><input type="radio" name="skinId" value="3">暗黑模式(安静、忧郁)</label></li>
  143. <li><label><input type="radio" name="skinId" value="4">vscode模式(醒目、专注)</label></li>
  144. <li><label><input type="radio" name="skinId" value="5">github模式(纵享丝滑)</label></li>
  145. <li><label><input type="radio" name="skinId" value="6">素人模式(清心寡欲)</label></li>
  146. </ul>
  147. <div class="btns">
  148. <input type="submit" class="xjf-btn" name="submit" value="确定">
  149. <input type="reset" class="xjf-btn" name="reset" value="取消">
  150. </div>
  151. </form>
  152. </div>`;
  153. let sPanel = $('#jfSettingPanel');
  154. if (!sPanel.length) {
  155. sPanel = $(html).appendTo('#jfToolbar');
  156. // 表单提交时,保存数据
  157. sPanel.find('input[type="submit"]').on('click', function (e) {
  158. e.preventDefault();
  159. e.stopPropagation();
  160. let formData = {};
  161. formData.JSON_PAGE_FORMAT = sPanel.find('input[name="alwaysOn"]').prop('checked');
  162. formData.JSON_TOOL_BAR_ALWAYS_SHOW = sPanel.find('input[name="alwaysShowToolbar"]').prop('checked');
  163. formData.STATUS_BAR_ALWAYS_SHOW = sPanel.find('input[name="alwaysShowStatusbar"]').prop('checked');
  164. formData.AUTO_TEXT_DECODE = sPanel.find('input[name="autoDecode"]').prop('checked');
  165. formData.FIX_ERROR_ENCODING = sPanel.find('input[name="errorEncoding"]').prop('checked');
  166. formData.ENABLE_JSON_KEY_SORT = sPanel.find('input[name="enableSort"]').prop('checked');
  167. formData.KEEP_KEY_VALUE_DBL_QUOTE = sPanel.find('input[name="keepQuote"]').prop('checked');
  168. formData.MAX_JSON_KEYS_NUMBER = sPanel.find('input[name="maxlength"]').val();
  169. formData.JSON_FORMAT_THEME = sPanel.find('input[name="skinId"]:checked').val();
  170. chrome.runtime.sendMessage({
  171. type: 'fh-dynamic-any-thing',
  172. thing: 'save-jsonformat-options',
  173. params: formData
  174. }, result => sPanel.hide());
  175. });
  176. sPanel.find('input[name="alwaysShowToolbar"]').on('click', function (e) {
  177. $('.fe-feedback #toggleBtn').trigger('click');
  178. });
  179. sPanel.find('input[name="errorEncoding"]').on('click', function (e) {
  180. let el = $('#jfToolbar').find('.x-fix-encoding');
  181. $(this).prop('checked') ? el.show() : el.hide();
  182. });
  183. sPanel.find('input[name="enableSort"]').on('click', function (e) {
  184. let el = $('#jfToolbar').find('.x-sort');
  185. $(this).prop('checked') ? el.show() : el.hide();
  186. });
  187. sPanel.find('input[type="reset"]').on('click', (e) => sPanel.hide());
  188. sPanel.find('input[name="skinId"]').on('click', function (e) {
  189. formatOptions.JSON_FORMAT_THEME = this.value;
  190. _didFormat();
  191. });
  192. sPanel.find('input[name="alwaysShowStatusbar"]').on('click', function (e) {
  193. formatOptions.STATUS_BAR_ALWAYS_SHOW = $(this).prop('checked');
  194. let elBody = $('body');
  195. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  196. elBody.removeClass('hide-status-bar');
  197. } else {
  198. elBody.addClass('hide-status-bar');
  199. }
  200. });
  201. sPanel.find('input[name="keepQuote"]').on('click', function (e) {
  202. formatOptions.KEEP_KEY_VALUE_DBL_QUOTE = $(this).prop('checked');
  203. let elBody = $('body');
  204. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  205. elBody.removeClass('remove-quote');
  206. } else {
  207. elBody.addClass('remove-quote');
  208. }
  209. });
  210. } else if (sPanel[0].offsetHeight) {
  211. return sPanel.hide();
  212. } else {
  213. sPanel.show();
  214. }
  215. _getAllOptions(result => {
  216. result.JSON_PAGE_FORMAT && sPanel.find('input[name="alwaysOn"]').prop('checked', true);
  217. result.JSON_TOOL_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowToolbar"]').prop('checked', true);
  218. result.STATUS_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowStatusbar"]').prop('checked', true);
  219. result.AUTO_TEXT_DECODE && sPanel.find('input[name="autoDecode"]').prop('checked', true);
  220. result.FIX_ERROR_ENCODING && sPanel.find('input[name="errorEncoding"]').prop('checked', true);
  221. result.ENABLE_JSON_KEY_SORT && sPanel.find('input[name="enableSort"]').prop('checked', true);
  222. result.KEEP_KEY_VALUE_DBL_QUOTE && sPanel.find('input[name="keepQuote"]').prop('checked', true);
  223. sPanel.find('input[name="maxlength"]').attr('value', result.MAX_JSON_KEYS_NUMBER || 10000);
  224. sPanel.find(`input[name="skinId"][value="${result.JSON_FORMAT_THEME || 0}"]`).attr('checked', true);
  225. });
  226. };
  227. // 检测当前页面的CSP,防止出现这种情况:
  228. // DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
  229. let _checkContentSecurityPolicy = () => {
  230. try {
  231. localStorage.getItem(1);
  232. } catch (e) {
  233. return false;
  234. }
  235. return true;
  236. };
  237. let _initToolbar = () => {
  238. let cspSafe = _checkContentSecurityPolicy();
  239. if (cspSafe) {
  240. // =============================排序:获取上次记录的排序方式
  241. if (formatOptions.ENABLE_JSON_KEY_SORT) {
  242. formatOptions.sortType = parseInt(localStorage.getItem(JSON_SORT_TYPE_KEY) || 0);
  243. // 排序选项初始化
  244. $('[name=jsonsort][value=' + formatOptions.sortType + ']').attr('checked', 1);
  245. } else {
  246. formatOptions.sortType = 0;
  247. $('#jfToolbar .x-sort').hide();
  248. }
  249. // =============================事件初始化
  250. $('[name=jsonsort]').click(function (e) {
  251. let sortType = parseInt(this.value);
  252. if (sortType !== formatOptions.sortType) {
  253. formatOptions.sortType = sortType;
  254. _didFormat();
  255. }
  256. localStorage.setItem(JSON_SORT_TYPE_KEY, sortType);
  257. });
  258. } else {
  259. $('#jfToolbar .x-sort').hide();
  260. }
  261. // =============================乱码修正
  262. if (!formatOptions.FIX_ERROR_ENCODING) {
  263. $('#jfToolbar .x-fix-encoding').hide();
  264. }
  265. // =============================工具栏的显示与隐藏控制
  266. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  267. let tgBtn = $('.fe-feedback #toggleBtn');
  268. if (formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW) {
  269. toolBarClassList.remove('t-collapse');
  270. tgBtn.html('隐藏&gt;&gt;');
  271. } else {
  272. toolBarClassList.add('t-collapse');
  273. tgBtn.html('&lt;&lt;');
  274. }
  275. tgBtn.click(function (e) {
  276. e.preventDefault();
  277. e.stopPropagation();
  278. chrome.runtime.sendMessage({
  279. type: 'fh-dynamic-any-thing',
  280. thing: 'toggle-jsonformat-options'
  281. }, show => {
  282. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  283. if (show) {
  284. toolBarClassList.remove('t-collapse');
  285. tgBtn.html('隐藏&gt;&gt;');
  286. } else {
  287. toolBarClassList.add('t-collapse');
  288. tgBtn.html('&lt;&lt;');
  289. }
  290. $('#jfToolbar input[name="alwaysShowToolbar"]').prop('checked', show);
  291. });
  292. });
  293. $('.fe-feedback .x-other-tools').on('click', function (e) {
  294. chrome.runtime.sendMessage({
  295. type: 'fh-dynamic-any-thing',
  296. thing: 'open-options-page'
  297. });
  298. });
  299. $('.fe-feedback .x-settings').click(e => _createSettingPanel());
  300. $('#jsonGetCorrectCnt').click(e => _getCorrectContent());
  301. $('.x-toolbar .x-donate-link').on('click', function (e) {
  302. chrome.runtime.sendMessage({
  303. type: 'fh-dynamic-any-thing',
  304. thing: 'open-donate-modal',
  305. params: { toolName: 'json-format' }
  306. });
  307. });
  308. };
  309. let _didFormat = function () {
  310. let source = formatOptions.originalSource;
  311. if (formatOptions.sortType !== 0) {
  312. let jsonObj = JsonABC.sortObj(JSON.parse(formatOptions.originalSource), parseInt(formatOptions.sortType), true);
  313. source = JSON.stringify(jsonObj);
  314. }
  315. let elBody = $('body');
  316. let theme = SKIN_THEME[formatOptions.JSON_FORMAT_THEME || 0];
  317. Object.values(SKIN_THEME).forEach(th => elBody.removeClass(th));
  318. elBody.addClass(theme);
  319. // 控制引号
  320. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  321. elBody.removeClass('remove-quote');
  322. } else {
  323. elBody.addClass('remove-quote');
  324. }
  325. // 控制底部状态栏
  326. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  327. elBody.removeClass('hide-status-bar');
  328. } else {
  329. elBody.addClass('hide-status-bar');
  330. }
  331. if (formatOptions.autoDecode) {
  332. (async () => {
  333. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  334. source = JsonEnDecode.uniDecode(txt);
  335. // 格式化
  336. try {
  337. Formatter.format(source, theme);
  338. } catch (e) {
  339. Formatter.formatSync(source, theme)
  340. }
  341. $('#jfToolbar').fadeIn(500);
  342. })();
  343. } else {
  344. // 格式化
  345. try {
  346. Formatter.format(source, theme);
  347. } catch (e) {
  348. Formatter.formatSync(source, theme)
  349. }
  350. $('#jfToolbar').fadeIn(500);
  351. }
  352. // 如果是JSONP格式的,需要把方法名也显示出来
  353. if (funcName != null) {
  354. if (fnTry && fnCatch) {
  355. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  356. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  357. } else {
  358. $('#jfCallbackName_start').html(funcName + '(');
  359. $('#jfCallbackName_end').html(')');
  360. }
  361. }
  362. };
  363. let _getCorrectContent = function () {
  364. fetch(location.href).then(res => res.text()).then(text => {
  365. formatOptions.originalSource = text;
  366. _didFormat();
  367. });
  368. };
  369. /**
  370. * 从一个dom节点去获取json内容,这里面有很多的判断
  371. */
  372. let _getJsonContentFromDOM = function (dom) {
  373. let source = dom.textContent.trim();
  374. if (!source) {
  375. source = (document.body.textContent || '').trim()
  376. }
  377. if (!source) {
  378. return false;
  379. }
  380. // 1、如果body的内容还包含HTML标签,肯定不是合法的json了
  381. // 2、如果是合法的json,也只可能有一个text节点
  382. // 3、但是要兼容一下其他插件对页面的破坏情况
  383. // 4、对于content-type是application/json的页面可以做宽松处理
  384. let nodes = document.body.childNodes;
  385. let jsonText = '';
  386. let isJsonContentType = document.contentType === 'application/json';
  387. for (let i = 0, len = nodes.length; i < len; i++) {
  388. let elm = nodes[i];
  389. if (elm.nodeType === Node.TEXT_NODE) {
  390. jsonText += (elm.textContent || '').trim();
  391. } else if (isJsonContentType) {
  392. if ((elm.offsetHeight + elm.offsetWidth !== 0) && elm.textContent.length > jsonText.length) {
  393. jsonText = elm.textContent;
  394. }
  395. } else {
  396. if (nodes[i].nodeType === Node.ELEMENT_NODE) {
  397. let tagName = elm.tagName.toLowerCase();
  398. let text = (elm.textContent || '').trim();
  399. // 如果包含了script和link标签,需要看标签的src和href属性值,如果不是chrome-extensions注入的,也要跳出
  400. if (['script', 'link'].includes(tagName)) {
  401. let url = elm.getAttribute('src') || elm.getAttribute('href');
  402. if (!!url && !/^chrome\-extension:\/\//.test(url)) {
  403. return false;
  404. }
  405. }
  406. // 如果不是pre标签,并且还不是隐藏节点,且内容不为空,也要跳出
  407. else if (tagName !== 'pre' && (elm.offsetWidth + elm.offsetHeight !== 0 && !!text)) {
  408. return false;
  409. }
  410. // 如果是pre标签,但当前节点内容与最初body.textContent提取值不一致,都跳出
  411. else if (tagName === 'pre' && text !== source) {
  412. return false;
  413. }
  414. } else {
  415. return false;
  416. }
  417. }
  418. }
  419. return (jsonText || '').trim() || source;
  420. };
  421. /**
  422. * 从页面提取JSON文本
  423. * @returns {string}
  424. * @private
  425. */
  426. let _getJsonText = function () {
  427. // 如果是js内容,则不进行json格式化
  428. let isJs = /\.js$/.test(new URL(location.href).pathname);
  429. isJs = isJs && document.contentType === 'application/javascript';
  430. if (isJs) {
  431. return false;
  432. }
  433. // 如果是 HTML 页面,也要看一下内容是不是明显就是个JSON,如果不是,则也不进行 json 格式化
  434. if (document.contentType === 'text/html') {
  435. // 使用 DOMParser 解析 HTML
  436. const parser = new DOMParser();
  437. const doc = parser.parseFromString(document.body.outerHTML, "text/html");
  438. // 移除不需要的标签
  439. doc.querySelectorAll('style, script').forEach(el => el.remove());
  440. // 获取清理后的文本
  441. const cleanText = doc.body.textContent;
  442. let jsonObj = _getJsonObject(cleanText);
  443. if(!jsonObj) {
  444. return false;
  445. }
  446. }
  447. let pre = document.querySelectorAll('body>pre')[0] || {textContent: ""};
  448. return _getJsonContentFromDOM(pre);
  449. };
  450. /**
  451. * 获取一个JSON的所有Key数量
  452. * @param json
  453. * @returns {number}
  454. * @private
  455. */
  456. let _getAllKeysCount = function (json) {
  457. let count = 0;
  458. if (typeof json === 'object') {
  459. let keys = Object.keys(json);
  460. count += keys.length;
  461. keys.forEach(key => {
  462. if (json[key] && typeof json[key] === 'object') {
  463. count += _getAllKeysCount(json[key]);
  464. }
  465. });
  466. }
  467. return count;
  468. };
  469. // 用新的options来覆盖默认options
  470. let _extendsOptions = options => {
  471. options = options || {};
  472. Object.keys(options).forEach(opt => formatOptions[opt] = options[opt]);
  473. };
  474. /**
  475. * 判断字符串参数是否为一个合法的json,如果是则返回json对象
  476. * @param {*} source
  477. * @returns
  478. */
  479. let _getJsonObject = function (source) {
  480. let jsonObj = null;
  481. // 下面校验给定字符串是否为一个合法的json
  482. try {
  483. // 再看看是不是jsonp的格式
  484. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
  485. let reTry = /^(try\s*\{\s*)?/g;
  486. let reCatch = /([;\s]*\}\s*catch\s*\(\s*\S+\s*\)\s*\{([\s\S])*\})?[;\s]*$/g;
  487. // 检测是否有try-catch包裹
  488. let sourceReplaced = source.replace(reTry, function () {
  489. fnTry = fnTry ? fnTry : arguments[1];
  490. return '';
  491. }).replace(reCatch, function () {
  492. fnCatch = fnCatch ? fnCatch : arguments[1];
  493. return '';
  494. }).trim();
  495. let matches = reg.exec(sourceReplaced);
  496. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  497. funcName = matches[1];
  498. source = matches[2];
  499. } else {
  500. reg = /^([\{\[])/;
  501. if (!reg.test(source)) {
  502. return;
  503. }
  504. }
  505. // 这里可能会throw exception
  506. jsonObj = JSON.parse(source);
  507. } catch (ex) {
  508. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  509. try {
  510. jsonObj = new Function("return " + source)();
  511. } catch (exx) {
  512. try {
  513. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  514. jsonObj = new Function("return '" + source + "'")();
  515. if (typeof jsonObj === 'string') {
  516. try {
  517. // 确保bigint不会失真
  518. jsonObj = JSON.parse(jsonObj);
  519. } catch (ie) {
  520. // 最后给你一次机会,是个字符串,老夫给你再转一次
  521. jsonObj = new Function("return " + jsonObj)();
  522. }
  523. }
  524. } catch (exxx) {
  525. return;
  526. }
  527. }
  528. }
  529. try {
  530. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  531. source = JSON.stringify(jsonObj);
  532. } catch (ex) {
  533. // 通过JSON反解不出来的,一定有问题
  534. return;
  535. }
  536. return jsonObj;
  537. };
  538. /**
  539. * 根据最终拿到的json source,对页面进行格式化操作
  540. * @param {*} source
  541. * @returns
  542. */
  543. let _formatTheSource = function (source) {
  544. let jsonObj = _getJsonObject(source);
  545. // 是json格式,可以进行JSON自动格式化
  546. if (jsonObj != null && typeof jsonObj === "object") {
  547. // 提前注入css
  548. if(!cssInjected) {
  549. chrome.runtime.sendMessage({
  550. type: 'fh-dynamic-any-thing',
  551. thing:'inject-content-css',
  552. tool: 'json-format'
  553. });
  554. cssInjected = true;
  555. }
  556. // JSON的所有key不能超过预设的值,比如 10000 个,要不然自动格式化会比较卡
  557. if (formatOptions['MAX_JSON_KEYS_NUMBER']) {
  558. let keysCount = _getAllKeysCount(jsonObj);
  559. if (keysCount > formatOptions['MAX_JSON_KEYS_NUMBER']) {
  560. let msg = '当前JSON共 <b style="color:red">' + keysCount + '</b> 个Key,大于预设值' + formatOptions['MAX_JSON_KEYS_NUMBER'] + ',已取消自动格式化;可到FeHelper设置页调整此配置!';
  561. return toast(msg);
  562. }
  563. }
  564. $('html').addClass('fh-jf');
  565. $('body').prepend(_getHtmlFragment());
  566. let preLength = $('body>pre').remove().length;
  567. if (!preLength) {
  568. Array.prototype.slice.call(document.body.childNodes).forEach(node => {
  569. (node.nodeType === Node.TEXT_NODE) && node.remove();
  570. });
  571. }
  572. formatOptions.originalSource = JSON.stringify(jsonObj);
  573. _initToolbar();
  574. _didFormat();
  575. }
  576. };
  577. /**
  578. * 执行format操作
  579. * @private
  580. */
  581. let _format = function () {
  582. let source = _getJsonText();
  583. if (source) {
  584. _formatTheSource(source);
  585. }
  586. };
  587. return {
  588. format: () => _getAllOptions(options => {
  589. if(options.JSON_PAGE_FORMAT) {
  590. let intervalId = setTimeout(() => {
  591. if(typeof Formatter !== 'undefined') {
  592. clearInterval(intervalId);
  593. _extendsOptions(options);
  594. _format();
  595. }
  596. },pleaseLetJsLoaded);
  597. }
  598. })
  599. };
  600. })();
  601. if(location.protocol !== 'chrome-extension:') {
  602. window.JsonAutoFormat.format();
  603. }