content-script.js 30 KB

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