content-script.js 30 KB

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