content-script.js 34 KB

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