content-script.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. /**
  2. * Json Page Automatic Format Via FeHelper
  3. * @author zhaoxianlie
  4. */
  5. window.JsonAutoFormat = (() => {
  6. // 依赖已在 background 首轮注入,这里无需再次加载
  7. let pleaseLetJsLoaded = 0;
  8. const JSON_SORT_TYPE_KEY = 'json_sort_type_key';
  9. // 本地永久存储的key
  10. const STORAGE_KEYS = {
  11. // 总是开启JSON自动格式化功能
  12. JSON_PAGE_FORMAT: 'JSON_PAGE_FORMAT',
  13. // 总是显示顶部工具栏
  14. JSON_TOOL_BAR_ALWAYS_SHOW: 'JSON_TOOL_BAR_ALWAYS_SHOW',
  15. // 启用底部状态栏
  16. STATUS_BAR_ALWAYS_SHOW: 'STATUS_BAR_ALWAYS_SHOW',
  17. // 自动进行URL、Unicode解码
  18. AUTO_TEXT_DECODE: 'AUTO_TEXT_DECODE',
  19. // 修正乱码
  20. FIX_ERROR_ENCODING: 'FIX_ERROR_ENCODING',
  21. // 启用JSON key排序功能
  22. ENABLE_JSON_KEY_SORT: 'ENABLE_JSON_KEY_SORT',
  23. // 保留键值双引号
  24. KEEP_KEY_VALUE_DBL_QUOTE: 'KEEP_KEY_VALUE_DBL_QUOTE',
  25. // 嵌套转义解析
  26. NESTED_ESCAPE_PARSE: 'NESTED_ESCAPE_PARSE',
  27. // 最大json key数量
  28. MAX_JSON_KEYS_NUMBER: 'MAX_JSON_KEYS_NUMBER',
  29. // 自定义皮肤
  30. JSON_FORMAT_THEME: 'JSON_FORMAT_THEME'
  31. };
  32. // 皮肤定义
  33. const SKIN_THEME = {
  34. '0': 'theme-default',
  35. '1': 'theme-simple',
  36. '2': 'theme-light',
  37. '3': 'theme-dark',
  38. '4': 'theme-vscode',
  39. '5': 'theme-github',
  40. '6': 'theme-vegetarian'
  41. };
  42. let cssInjected = false;
  43. // JSONP形式下的callback name
  44. let funcName = null;
  45. let fnTry = null;
  46. let fnCatch = null;
  47. // 工具栏是否显示
  48. let showToolBar = true;
  49. // 格式化的配置
  50. let formatOptions = {
  51. JSON_FORMAT_THEME: 0,
  52. sortType: 0,
  53. autoDecode: false,
  54. originalSource: '',
  55. NESTED_ESCAPE_PARSE: false
  56. };
  57. // 获取JSON格式化的配置信息
  58. let _getAllOptions = (success) => {
  59. chrome.runtime.sendMessage({
  60. type: 'fh-dynamic-any-thing',
  61. thing:'request-jsonformat-options',
  62. params: STORAGE_KEYS
  63. }, result => success(result));
  64. };
  65. let _getHtmlFragment = () => {
  66. // 判断当前地区是否在美国
  67. const isInUSA = () => {
  68. // 通过时区判断是否在美国
  69. const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  70. const isUSTimeZone = /^America\/(New_York|Chicago|Denver|Los_Angeles|Anchorage|Honolulu)/.test(timeZone);
  71. // 通过语言判断
  72. const language = navigator.language || navigator.userLanguage;
  73. const isUSLanguage = language.toLowerCase().indexOf('en-us') > -1;
  74. // 如果时区和语言都符合美国特征,则认为在美国
  75. return (isUSTimeZone && isUSLanguage);
  76. };
  77. return [
  78. '<div id="jfToolbar" class="x-toolbar" style="display:none">' +
  79. ' <a href="https://fehelper.com" target="_blank" class="x-a-title">' +
  80. ' <img src="' + chrome.runtime.getURL('static/img/fe-16.png') + '" alt="fehelper"/> FeHelper</a>' +
  81. ' <span class="x-b-title"></span>' +
  82. ' <span class="x-sort">' +
  83. ' <span class="x-split">|</span>' +
  84. ' <span class="x-stitle">排序:</span>' +
  85. ' <label for="sort_null">默认</label><input type="radio" name="jsonsort" id="sort_null" value="0" checked>' +
  86. ' <label for="sort_asc">升序</label><input type="radio" name="jsonsort" id="sort_asc" value="1">' +
  87. ' <label for="sort_desc">降序</label><input type="radio" name="jsonsort" id="sort_desc" value="-1">' +
  88. ' <label for="nestedEscapeParseToggle">嵌套转义解析</label><input type="checkbox" id="nestedEscapeParseToggle">' +
  89. ' </span>' +
  90. ' <span class="x-fix-encoding"><span class="x-split">|</span><button class="xjf-btn" id="jsonGetCorrectCnt">乱码修正</button></span>' +
  91. ' <span id="optionBar"></span>' +
  92. ' <span class="fe-feedback">' +
  93. ' <span class="x-settings"><svg aria-hidden="true" height="16" version="1.1" viewBox="0 0 14 16" width="14">' +
  94. ' <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>' +
  95. ' </svg>高级定制</span>' +
  96. ' <a id="toggleBtn" title="展开或收起工具栏">隐藏&gt;&gt;</a>' +
  97. ' <span class="x-donate-link' + (isInUSA() ? ' x-donate-link-us' : '') + '"><a href="#" id="donateLink"><i class="nav-icon">❤</i>&nbsp;打赏鼓励</a></span>' +
  98. ' <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>' +
  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. // 同步更新当前页面的formatOptions对象
  158. Object.keys(formData).forEach(key => {
  159. formatOptions[key] = formData[key];
  160. });
  161. chrome.runtime.sendMessage({
  162. type: 'fh-dynamic-any-thing',
  163. thing: 'save-jsonformat-options',
  164. params: formData
  165. }, result => {
  166. sPanel.hide();
  167. // 重新应用格式化以展示最新设置
  168. _didFormat();
  169. });
  170. });
  171. sPanel.find('input[name="alwaysShowToolbar"]').on('click', function (e) {
  172. $('.fe-feedback #toggleBtn').trigger('click');
  173. });
  174. sPanel.find('input[name="errorEncoding"]').on('click', function (e) {
  175. let el = $('#jfToolbar').find('.x-fix-encoding');
  176. $(this).prop('checked') ? el.show() : el.hide();
  177. });
  178. sPanel.find('input[name="enableSort"]').on('click', function (e) {
  179. let el = $('#jfToolbar').find('.x-sort');
  180. $(this).prop('checked') ? el.show() : el.hide();
  181. });
  182. sPanel.find('input[type="reset"]').on('click', (e) => sPanel.hide());
  183. sPanel.find('input[name="skinId"]').on('click', function (e) {
  184. formatOptions.JSON_FORMAT_THEME = this.value;
  185. _didFormat();
  186. });
  187. sPanel.find('input[name="alwaysShowStatusbar"]').on('click', function (e) {
  188. formatOptions.STATUS_BAR_ALWAYS_SHOW = $(this).prop('checked');
  189. let elBody = $('body');
  190. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  191. elBody.removeClass('hide-status-bar');
  192. } else {
  193. elBody.addClass('hide-status-bar');
  194. }
  195. });
  196. sPanel.find('input[name="keepQuote"]').on('click', function (e) {
  197. formatOptions.KEEP_KEY_VALUE_DBL_QUOTE = $(this).prop('checked');
  198. let elBody = $('body');
  199. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  200. elBody.removeClass('remove-quote');
  201. } else {
  202. elBody.addClass('remove-quote');
  203. }
  204. });
  205. } else if (sPanel[0].offsetHeight) {
  206. return sPanel.hide();
  207. } else {
  208. sPanel.show();
  209. }
  210. _getAllOptions(result => {
  211. result.JSON_PAGE_FORMAT && sPanel.find('input[name="alwaysOn"]').prop('checked', true);
  212. result.JSON_TOOL_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowToolbar"]').prop('checked', true);
  213. result.STATUS_BAR_ALWAYS_SHOW && sPanel.find('input[name="alwaysShowStatusbar"]').prop('checked', true);
  214. result.AUTO_TEXT_DECODE && sPanel.find('input[name="autoDecode"]').prop('checked', true);
  215. result.FIX_ERROR_ENCODING && sPanel.find('input[name="errorEncoding"]').prop('checked', true);
  216. result.ENABLE_JSON_KEY_SORT && sPanel.find('input[name="enableSort"]').prop('checked', true);
  217. result.KEEP_KEY_VALUE_DBL_QUOTE && sPanel.find('input[name="keepQuote"]').prop('checked', true);
  218. sPanel.find('input[name="maxlength"]').attr('value', result.MAX_JSON_KEYS_NUMBER || 10000);
  219. sPanel.find(`input[name="skinId"][value="${result.JSON_FORMAT_THEME || 0}"]`).attr('checked', true);
  220. });
  221. };
  222. // 检测当前页面的CSP,防止出现这种情况:
  223. // DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
  224. let _checkContentSecurityPolicy = () => {
  225. try {
  226. localStorage.getItem(1);
  227. } catch (e) {
  228. return false;
  229. }
  230. return true;
  231. };
  232. let _initToolbar = () => {
  233. showToolBar = formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW;
  234. let cspSafe = _checkContentSecurityPolicy();
  235. if (cspSafe) {
  236. // =============================排序:获取上次记录的排序方式
  237. if (formatOptions.ENABLE_JSON_KEY_SORT) {
  238. formatOptions.sortType = parseInt(localStorage.getItem(JSON_SORT_TYPE_KEY) || 0);
  239. // 排序选项初始化
  240. $('[name=jsonsort][value=' + formatOptions.sortType + ']').attr('checked', 1);
  241. } else {
  242. formatOptions.sortType = 0;
  243. $('#jfToolbar .x-sort').hide();
  244. }
  245. // =============================事件初始化
  246. $('[name=jsonsort]').click(function (e) {
  247. let sortType = parseInt(this.value);
  248. if (sortType !== formatOptions.sortType) {
  249. formatOptions.sortType = sortType;
  250. _didFormat();
  251. }
  252. localStorage.setItem(JSON_SORT_TYPE_KEY, sortType);
  253. });
  254. } else {
  255. $('#jfToolbar .x-sort').hide();
  256. }
  257. let nestedToggle = $('#nestedEscapeParseToggle');
  258. nestedToggle.prop('checked', !!formatOptions.NESTED_ESCAPE_PARSE);
  259. if (typeof window.Formatter !== 'undefined' && window.Formatter.setEscapeEnabled) {
  260. window.Formatter.setEscapeEnabled(!!formatOptions.NESTED_ESCAPE_PARSE);
  261. }
  262. nestedToggle.off('change').on('change', function () {
  263. let enabled = $(this).prop('checked');
  264. formatOptions.NESTED_ESCAPE_PARSE = enabled;
  265. if (typeof window.Formatter !== 'undefined' && window.Formatter.setEscapeEnabled) {
  266. window.Formatter.setEscapeEnabled(enabled);
  267. }
  268. chrome.runtime.sendMessage({
  269. type: 'fh-dynamic-any-thing',
  270. thing: 'save-jsonformat-options',
  271. params: {
  272. NESTED_ESCAPE_PARSE: enabled
  273. }
  274. });
  275. _didFormat();
  276. });
  277. // =============================乱码修正
  278. if (!formatOptions.FIX_ERROR_ENCODING) {
  279. $('#jfToolbar .x-fix-encoding').hide();
  280. }
  281. // =============================工具栏的显示与隐藏控制
  282. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  283. let tgBtn = $('.fe-feedback #toggleBtn');
  284. if (formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW) {
  285. toolBarClassList.remove('t-collapse');
  286. tgBtn.html('隐藏&gt;&gt;');
  287. } else {
  288. toolBarClassList.add('t-collapse');
  289. tgBtn.html('&lt;&lt;');
  290. }
  291. tgBtn.click(function (e) {
  292. e.preventDefault();
  293. e.stopPropagation();
  294. let toolBarClassList = document.querySelector('#jfToolbar').classList;
  295. showToolBar = !showToolBar;
  296. if (showToolBar) {
  297. toolBarClassList.remove('t-collapse');
  298. tgBtn.html('隐藏&gt;&gt;');
  299. formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW = true;
  300. } else {
  301. toolBarClassList.add('t-collapse');
  302. tgBtn.html('&lt;&lt;');
  303. formatOptions.JSON_TOOL_BAR_ALWAYS_SHOW = false;
  304. }
  305. $('#jfToolbar input[name="alwaysShowToolbar"]').prop('checked', showToolBar);
  306. });
  307. $('.fe-feedback .x-other-tools').on('click', function (e) {
  308. chrome.runtime.sendMessage({
  309. type: 'fh-dynamic-any-thing',
  310. thing: 'open-options-page'
  311. });
  312. });
  313. $('.fe-feedback .x-settings').click(e => _createSettingPanel());
  314. $('#jsonGetCorrectCnt').click(e => _getCorrectContent());
  315. $('.x-toolbar .x-donate-link').on('click', function (e) {
  316. chrome.runtime.sendMessage({
  317. type: 'fh-dynamic-any-thing',
  318. thing: 'open-donate-modal',
  319. params: { toolName: 'json-format' }
  320. });
  321. });
  322. };
  323. let _didFormat = function () {
  324. let source = formatOptions.originalSource;
  325. if (formatOptions.sortType !== 0) {
  326. let jsonObj = JsonABC.sortObj(JSON.parse(formatOptions.originalSource), parseInt(formatOptions.sortType), true);
  327. source = JSON.stringify(jsonObj);
  328. }
  329. let elBody = $('body');
  330. let theme = SKIN_THEME[formatOptions.JSON_FORMAT_THEME || 0];
  331. Object.values(SKIN_THEME).forEach(th => elBody.removeClass(th));
  332. elBody.addClass(theme);
  333. // 控制引号
  334. if (formatOptions.KEEP_KEY_VALUE_DBL_QUOTE) {
  335. elBody.removeClass('remove-quote');
  336. } else {
  337. elBody.addClass('remove-quote');
  338. }
  339. // 控制底部状态栏
  340. if (formatOptions.STATUS_BAR_ALWAYS_SHOW) {
  341. elBody.removeClass('hide-status-bar');
  342. } else {
  343. elBody.addClass('hide-status-bar');
  344. }
  345. // 检查是否在受限域名,直接使用同步模式
  346. const currentUrl = window.location.href;
  347. const restrictedDomains = ['gitee.com', 'github.com', 'raw.githubusercontent.com'];
  348. const isRestrictedDomain = restrictedDomains.some(domain => currentUrl.includes(domain));
  349. if (isRestrictedDomain) {
  350. console.log('检测到受限域名,直接使用同步模式');
  351. if (formatOptions.autoDecode) {
  352. (async () => {
  353. try {
  354. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  355. source = JsonEnDecode.uniDecode(txt);
  356. } catch (e) {
  357. console.warn('URL解码失败,使用原始内容:', e);
  358. }
  359. Formatter.formatSync(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  360. $('#jfToolbar').show();
  361. })();
  362. } else {
  363. Formatter.formatSync(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  364. $('#jfToolbar').show();
  365. }
  366. } else if (formatOptions.autoDecode) {
  367. (async () => {
  368. try {
  369. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  370. source = JsonEnDecode.uniDecode(txt);
  371. } catch (e) {
  372. console.warn('URL解码失败,使用原始内容:', e);
  373. }
  374. // 格式化
  375. try {
  376. await Formatter.format(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  377. } catch (e) {
  378. console.warn('异步格式化失败,使用同步模式:', e);
  379. Formatter.formatSync(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  380. }
  381. $('#jfToolbar').show();
  382. })();
  383. } else {
  384. (async () => {
  385. // 格式化
  386. try {
  387. await Formatter.format(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  388. } catch (e) {
  389. console.warn('异步格式化失败,使用同步模式:', e);
  390. Formatter.formatSync(source, theme, formatOptions.NESTED_ESCAPE_PARSE);
  391. }
  392. $('#jfToolbar').show();
  393. })();
  394. }
  395. // 如果是JSONP格式的,需要把方法名也显示出来
  396. if (funcName != null) {
  397. if (fnTry && fnCatch) {
  398. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  399. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  400. } else {
  401. $('#jfCallbackName_start').html(funcName + '(');
  402. $('#jfCallbackName_end').html(')');
  403. }
  404. }
  405. // 埋点:自动触发json-format-auto
  406. chrome.runtime.sendMessage({
  407. type: 'fh-dynamic-any-thing',
  408. thing: 'statistics-tool-usage',
  409. params: {
  410. tool_name: 'json-format',
  411. url: location.href
  412. }
  413. });
  414. };
  415. let _getCorrectContent = function () {
  416. fetch(location.href).then(res => res.text()).then(text => {
  417. formatOptions.originalSource = text;
  418. _didFormat();
  419. });
  420. };
  421. /**
  422. * 从一个dom节点去获取json内容,这里面有很多的判断
  423. */
  424. let _getJsonContentFromDOM = function (dom) {
  425. let source = dom.textContent.trim();
  426. if (!source && document.body) {
  427. source = (document.body.textContent || '').trim()
  428. }
  429. if (!source) {
  430. return false;
  431. }
  432. // 1、如果body的内容还包含HTML标签,肯定不是合法的json了
  433. // 2、如果是合法的json,也只可能有一个text节点
  434. // 3、但是要兼容一下其他插件对页面的破坏情况
  435. // 4、对于content-type是application/json的页面可以做宽松处理
  436. let nodes = document.body.childNodes;
  437. let jsonText = '';
  438. let isJsonContentType = document.contentType === 'application/json';
  439. for (let i = 0, len = nodes.length; i < len; i++) {
  440. let elm = nodes[i];
  441. if (elm.nodeType === Node.TEXT_NODE) {
  442. jsonText += (elm.textContent || '').trim();
  443. } else if (isJsonContentType) {
  444. if ((elm.offsetHeight + elm.offsetWidth !== 0) && elm.textContent.length > jsonText.length) {
  445. jsonText = elm.textContent;
  446. }
  447. } else {
  448. if (nodes[i].nodeType === Node.ELEMENT_NODE) {
  449. let tagName = elm.tagName.toLowerCase();
  450. let text = (elm.textContent || '').trim();
  451. // 如果包含了script和link标签,需要看标签的src和href属性值,如果不是chrome-extensions注入的,也要跳出
  452. if (['script', 'link'].includes(tagName)) {
  453. let url = elm.getAttribute('src') || elm.getAttribute('href');
  454. if (!!url && !/^chrome\-extension:\/\//.test(url)) {
  455. return false;
  456. }
  457. }
  458. // 如果不是pre标签,并且还不是隐藏节点,且内容不为空,也要跳出
  459. else if (tagName !== 'pre' && (elm.offsetWidth + elm.offsetHeight !== 0 && !!text)) {
  460. return false;
  461. }
  462. // 如果是pre标签,但当前节点内容与最初body.textContent提取值不一致,都跳出
  463. else if (tagName === 'pre' && text !== source) {
  464. return false;
  465. }
  466. } else {
  467. return false;
  468. }
  469. }
  470. }
  471. return (jsonText || '').trim() || source;
  472. };
  473. /**
  474. * 从页面提取JSON文本
  475. * @returns {string}
  476. * @private
  477. */
  478. let _getJsonText = function () {
  479. // 如果是js内容,则不进行json格式化
  480. let isJs = /\.js$/.test(new URL(location.href).pathname);
  481. isJs = isJs && document.contentType === 'application/javascript';
  482. if (isJs) {
  483. return false;
  484. }
  485. // 如果是 HTML 页面,也要看一下内容是不是明显就是个JSON,如果不是,则也不进行 json 格式化
  486. if (document.contentType === 'text/html' && document.body) {
  487. // 使用 DOMParser 解析 HTML
  488. const parser = new DOMParser();
  489. const doc = parser.parseFromString(document.body.outerHTML, "text/html");
  490. // 移除不需要的标签
  491. doc.querySelectorAll('style, script').forEach(el => el.remove());
  492. // 获取清理后的文本
  493. const cleanText = doc.body.textContent;
  494. let jsonObj = _getJsonObject(cleanText);
  495. if(!jsonObj) {
  496. return false;
  497. }
  498. }
  499. let pre = document.querySelectorAll('body>pre')[0] || {textContent: ""};
  500. return _getJsonContentFromDOM(pre);
  501. };
  502. /**
  503. * 获取一个JSON的所有Key数量
  504. * @param json
  505. * @returns {number}
  506. * @private
  507. */
  508. let _getAllKeysCount = function (json) {
  509. let count = 0;
  510. if (typeof json === 'object') {
  511. let keys = Object.keys(json);
  512. count += keys.length;
  513. keys.forEach(key => {
  514. if (json[key] && typeof json[key] === 'object') {
  515. count += _getAllKeysCount(json[key]);
  516. }
  517. });
  518. }
  519. return count;
  520. };
  521. // 用新的options来覆盖默认options
  522. let _extendsOptions = options => {
  523. options = options || {};
  524. Object.keys(options).forEach(opt => formatOptions[opt] = options[opt]);
  525. if (options.hasOwnProperty('AUTO_TEXT_DECODE')) {
  526. formatOptions.autoDecode = !!options.AUTO_TEXT_DECODE;
  527. } else if (formatOptions.hasOwnProperty('AUTO_TEXT_DECODE')) {
  528. formatOptions.autoDecode = !!formatOptions.AUTO_TEXT_DECODE;
  529. }
  530. if (options.hasOwnProperty('NESTED_ESCAPE_PARSE')) {
  531. formatOptions.NESTED_ESCAPE_PARSE = !!options.NESTED_ESCAPE_PARSE;
  532. } else if (formatOptions.hasOwnProperty('NESTED_ESCAPE_PARSE')) {
  533. formatOptions.NESTED_ESCAPE_PARSE = !!formatOptions.NESTED_ESCAPE_PARSE;
  534. }
  535. };
  536. /**
  537. * 判断字符串参数是否为一个合法的json,如果是则返回json对象
  538. * @param {*} source
  539. * @returns
  540. */
  541. let _getJsonObject = function (source) {
  542. let jsonObj = null;
  543. // 下面校验给定字符串是否为一个合法的json
  544. try {
  545. // 再看看是不是jsonp的格式
  546. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/m;
  547. // 优化后的 try/catch 包裹处理
  548. fnTry = null;
  549. fnCatch = null;
  550. // 处理开头
  551. if (source.startsWith('try {')) {
  552. fnTry = 'try {';
  553. source = source.slice(5).trimStart();
  554. }
  555. // 处理结尾
  556. let catchIdx = source.lastIndexOf('} catch');
  557. if (catchIdx !== -1) {
  558. // 找到最后一个 } catch,截取到末尾
  559. fnCatch = source.slice(catchIdx);
  560. source = source.slice(0, catchIdx).trimEnd();
  561. }
  562. // 只做一次正则匹配
  563. let matches = reg.exec(source);
  564. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  565. funcName = matches[1];
  566. source = matches[2];
  567. } else {
  568. reg = /^([\{\[])/;
  569. if (!reg.test(source)) {
  570. return;
  571. }
  572. }
  573. // 这里可能会throw exception
  574. jsonObj = JSON.parse(source);
  575. } catch (ex) {
  576. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  577. try {
  578. jsonObj = new Function("return " + source)();
  579. } catch (exx) {
  580. try {
  581. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  582. jsonObj = new Function("return '" + source + "'")();
  583. if (typeof jsonObj === 'string') {
  584. try {
  585. // 确保bigint不会失真
  586. jsonObj = JSON.parse(jsonObj);
  587. } catch (ie) {
  588. // 最后给你一次机会,是个字符串,老夫给你再转一次
  589. jsonObj = new Function("return " + jsonObj)();
  590. }
  591. }
  592. } catch (exxx) {
  593. return;
  594. }
  595. }
  596. }
  597. try {
  598. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  599. source = JSON.stringify(jsonObj);
  600. } catch (ex) {
  601. // 通过JSON反解不出来的,一定有问题
  602. return;
  603. }
  604. return jsonObj;
  605. };
  606. /**
  607. * 根据最终拿到的json source,对页面进行格式化操作
  608. * @param {*} source
  609. * @returns
  610. */
  611. let _formatTheSource = function (source) {
  612. let jsonObj = _getJsonObject(source);
  613. // 是json格式,可以进行JSON自动格式化
  614. if (jsonObj != null && typeof jsonObj === "object") {
  615. // 提前注入css
  616. if(!cssInjected) {
  617. chrome.runtime.sendMessage({
  618. type: 'fh-dynamic-any-thing',
  619. thing:'inject-content-css',
  620. tool: 'json-format'
  621. });
  622. cssInjected = true;
  623. }
  624. // JSON的所有key不能超过预设的值,比如 10000 个,要不然自动格式化会比较卡
  625. if (formatOptions['MAX_JSON_KEYS_NUMBER']) {
  626. let keysCount = _getAllKeysCount(jsonObj);
  627. if (keysCount > formatOptions['MAX_JSON_KEYS_NUMBER']) {
  628. let msg = '当前JSON共 <b style="color:red">' + keysCount + '</b> 个Key,大于预设值' + formatOptions['MAX_JSON_KEYS_NUMBER'] + ',已取消自动格式化;可到FeHelper设置页调整此配置!';
  629. return toast(msg);
  630. }
  631. }
  632. $('html').addClass('fh-jf');
  633. $('body').prepend(_getHtmlFragment());
  634. let preLength = $('body>pre').remove().length;
  635. if (!preLength) {
  636. Array.prototype.slice.call(document.body.childNodes).forEach(node => {
  637. (node.nodeType === Node.TEXT_NODE) && node.remove();
  638. });
  639. }
  640. formatOptions.originalSource = JSON.stringify(jsonObj);
  641. // 确保从storage加载最新设置
  642. _getAllOptions(options => {
  643. _extendsOptions(options);
  644. _initToolbar();
  645. _didFormat();
  646. });
  647. }
  648. };
  649. /**
  650. * 执行format操作
  651. * @private
  652. */
  653. let _format = function () {
  654. let source = _getJsonText();
  655. if (source) {
  656. _formatTheSource(source);
  657. }
  658. };
  659. // 页面加载后自动采集
  660. try {
  661. if (window.chrome && chrome.runtime && chrome.runtime.sendMessage && window.Awesome && window.Awesome.collectAndSendClientInfo) {
  662. window.Awesome.collectAndSendClientInfo();
  663. } else {
  664. // fallback: 动态加载Awesome模块
  665. import(chrome.runtime.getURL('background/awesome.js')).then(module => {
  666. module.default.collectAndSendClientInfo();
  667. }).catch(() => {});
  668. }
  669. } catch(e) {}
  670. return {
  671. format: () => _getAllOptions(options => {
  672. if(options.JSON_PAGE_FORMAT) {
  673. let intervalId = setTimeout(() => {
  674. if(typeof Formatter !== 'undefined') {
  675. clearInterval(intervalId);
  676. // 加载所有保存的配置
  677. _extendsOptions(options);
  678. // 应用格式化
  679. _format();
  680. }
  681. },pleaseLetJsLoaded);
  682. }
  683. })
  684. };
  685. })();
  686. if(location.protocol !== 'chrome-extension:') {
  687. (async () => {
  688. await window.JsonAutoFormat.format();
  689. })();
  690. }