1
0

format-lib.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. /**
  2. * FeHelper Json Format Lib
  3. */
  4. let JsonFormatEntrance = (function () {
  5. "use strict";
  6. let jfContent,
  7. jfPre,
  8. jfStyleEl,
  9. jfOptEl,
  10. jfPathEl,
  11. formattingMsg;
  12. let lastKvovIdGiven = 0;
  13. let cachedJsonString = '';
  14. let _initElements = function () {
  15. jfContent = $('#jfContent');
  16. if (!jfContent[0]) {
  17. jfContent = $('<div id="jfContent" />').appendTo('body');
  18. }
  19. jfPre = $('#jfContent_pre');
  20. if (!jfPre[0]) {
  21. jfPre = $('<pre id="jfContent_pre" />').appendTo('body');
  22. }
  23. jfStyleEl = $('#jfStyleEl');
  24. if (!jfStyleEl[0]) {
  25. jfStyleEl = $('<style id="jfStyleEl" />').appendTo('head');
  26. }
  27. formattingMsg = $('#formattingMsg');
  28. if (!formattingMsg[0]) {
  29. formattingMsg = $('<div id="formattingMsg"><span class="x-loading"></span>格式化中...</div>').appendTo('body');
  30. }
  31. jfOptEl = $('#boxOpt');
  32. if (!jfOptEl.length) {
  33. jfOptEl = $('<div id="boxOpt"><a class="opt-download" target="_blank">下载</a>|<a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  34. }
  35. try {
  36. jfContent.html('').show();
  37. jfPre.html('').hide();
  38. jfOptEl && jfOptEl.hide();
  39. jfPathEl && jfPathEl.hide();
  40. formattingMsg.hide();
  41. } catch (e) {
  42. }
  43. };
  44. // Add listener to receive response from BG when ready
  45. let postMessage = function (msg) {
  46. switch (msg[0]) {
  47. case 'NOT JSON' :
  48. jfPre.show();
  49. jfContent.html('<span class="x-json-tips">JSON不合法,请检查:</span>');
  50. break;
  51. case 'FORMATTING' :
  52. formattingMsg.show();
  53. break;
  54. case 'FORMATTED' :
  55. formattingMsg.hide();
  56. jfContent.html(msg[1]);
  57. _loadJs();
  58. _buildOptionBar();
  59. // 事件绑定
  60. _addEvents();
  61. // 支持文件下载
  62. _downloadSupport(cachedJsonString);
  63. break;
  64. default :
  65. throw new Error('Message not understood: ' + msg[0]);
  66. }
  67. };
  68. /**
  69. * 执行代码格式化
  70. * @param {[type]} jsonStr [description]
  71. * @return {[type]}
  72. */
  73. let format = function (jsonStr) {
  74. cachedJsonString = JSON.stringify(JSON.parse(jsonStr), null, 4);
  75. _initElements();
  76. jfPre.html(cachedJsonString);
  77. JsonFormatDealer.postMessage({
  78. type: "SENDING TEXT",
  79. text: jsonStr,
  80. length: jsonStr.length
  81. });
  82. };
  83. let _loadJs = function () {
  84. if (typeof Tarp === 'object') {
  85. Tarp.require('../static/js/utils.js');
  86. } else {
  87. alert('无法加载Tarp.require.js');
  88. }
  89. };
  90. /**
  91. * 直接下载,能解决中文乱码
  92. * @param content
  93. * @private
  94. */
  95. let _downloadSupport = function (content) {
  96. // 下载链接
  97. let dt = (new Date()).format('yyyyMMddHHmmss');
  98. let blob = new Blob([content], {type: 'application/octet-stream'});
  99. let button = $('<button id="btnDownload">下载JSON</button>').appendTo('#optionBar');
  100. if (typeof chrome === 'undefined' || !chrome.permissions) {
  101. button.click(function (e) {
  102. let aLink = $('<a id="btnDownload" target="_blank" title="保存到本地">下载JSON数据</a>');
  103. aLink.attr('download', 'FeHelper-' + dt + '.json');
  104. aLink.attr('href', URL.createObjectURL(blob));
  105. aLink[0].click();
  106. });
  107. } else {
  108. button.click(function (e) {
  109. // 请求权限
  110. chrome.permissions.request({
  111. permissions: ['downloads']
  112. }, (granted) => {
  113. if (granted) {
  114. chrome.downloads.download({
  115. url: URL.createObjectURL(blob),
  116. saveAs: true,
  117. conflictAction: 'overwrite',
  118. filename: 'FeHelper-' + dt + '.json'
  119. });
  120. } else {
  121. alert('必须接受授权,才能正常下载!');
  122. }
  123. });
  124. });
  125. }
  126. };
  127. /**
  128. * chrome 下复制到剪贴板
  129. * @param text
  130. */
  131. let _copyToClipboard = function (text) {
  132. let input = document.createElement('textarea');
  133. input.style.position = 'fixed';
  134. input.style.opacity = 0;
  135. input.value = text;
  136. document.body.appendChild(input);
  137. input.select();
  138. document.execCommand('Copy');
  139. document.body.removeChild(input);
  140. alert('Json片段复制成功,随处粘贴可用!')
  141. };
  142. /**
  143. * 从el中获取json文本
  144. * @param el
  145. * @returns {string}
  146. */
  147. let getJsonText = function (el) {
  148. let txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  149. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  150. txt = '{' + txt + '}';
  151. }
  152. try {
  153. txt = JSON.stringify(JSON.parse(txt), null, 4);
  154. } catch (err) {
  155. }
  156. return txt;
  157. };
  158. /**
  159. * 给某个节点增加操作项
  160. * @param el
  161. * @private
  162. */
  163. let _addOptForItem = function (el) {
  164. // 下载json片段
  165. let fnDownload = function (ec) {
  166. let txt = getJsonText(el);
  167. // 下载片段
  168. let dt = (new Date()).format('yyyyMMddHHmmss');
  169. let blob = new Blob([txt], {type: 'application/octet-stream'});
  170. if (typeof chrome === 'undefined' || !chrome.permissions) {
  171. // 下载JSON的简单形式
  172. $(this).attr('download', 'FeHelper-' + dt + '.json').attr('href', URL.createObjectURL(blob));
  173. } else {
  174. // 请求权限
  175. chrome.permissions.request({
  176. permissions: ['downloads']
  177. }, (granted) => {
  178. if (granted) {
  179. chrome.downloads.download({
  180. url: URL.createObjectURL(blob),
  181. saveAs: true,
  182. conflictAction: 'overwrite',
  183. filename: 'FeHelper-' + dt + '.json'
  184. });
  185. } else {
  186. alert('必须接受授权,才能正常下载!');
  187. }
  188. });
  189. }
  190. };
  191. // 复制json片段
  192. let fnCopy = function (ec) {
  193. _copyToClipboard(getJsonText(el));
  194. };
  195. // 删除json片段
  196. let fnDel = function (ed) {
  197. if (el.parent().is('#formattedJson')) {
  198. alert('如果连最外层的Json也删掉的话,就没啥意义了哦!');
  199. return false;
  200. }
  201. alert('节点已删除成功!');
  202. el.remove();
  203. jfOptEl.css('top', -1000).hide();
  204. jfPathEl && jfPathEl.hide();
  205. };
  206. jfOptEl.find('a.opt-download').unbind('click').bind('click', fnDownload);
  207. jfOptEl.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  208. jfOptEl.find('a.opt-del').unbind('click').bind('click', fnDel);
  209. jfOptEl.css({
  210. left: el.offset().left + el.width() - 90,
  211. top: el.offset().top
  212. }).show();
  213. };
  214. /**
  215. * 折叠所有
  216. * @param elements
  217. */
  218. function collapse(elements) {
  219. let el;
  220. $.each(elements, function (i) {
  221. el = $(this);
  222. if (el.children('.blockInner').length) {
  223. el.addClass('collapsed');
  224. if (!el.attr('id')) {
  225. el.attr('id', 'kvov' + (++lastKvovIdGiven));
  226. let count = el.children('.blockInner').eq(0).children().length;
  227. // Generate comment text eg "4 items"
  228. let comment = count + (count === 1 ? ' item' : ' items');
  229. // Add CSS that targets it
  230. jfStyleEl[0].insertAdjacentHTML(
  231. 'beforeend',
  232. '\n#kvov' + lastKvovIdGiven + '.collapsed:after{color: #aaa; content:" // ' + comment + '"}'
  233. );
  234. }
  235. }
  236. });
  237. }
  238. /**
  239. * 创建几个全局操作的按钮,置于页面右上角即可
  240. * @private
  241. */
  242. let _buildOptionBar = function () {
  243. let optionBar = $('#optionBar');
  244. if (optionBar) {
  245. optionBar.remove();
  246. }
  247. optionBar = $('<div id="optionBar" />').appendTo(jfContent.parent());
  248. let buttonFormatted = $('<button id="buttonFormatted">元数据</button>').appendTo(optionBar);
  249. let buttonCollapseAll = $('<button id="buttonCollapseAll">折叠所有</button>').appendTo(optionBar);
  250. let plainOn = false;
  251. buttonFormatted.bind('click', function (e) {
  252. if (plainOn) {
  253. plainOn = false;
  254. jfPre.hide();
  255. jfContent.show();
  256. buttonFormatted.text('元数据');
  257. } else {
  258. plainOn = true;
  259. jfPre.show();
  260. jfContent.hide();
  261. buttonFormatted.text('格式化');
  262. }
  263. jfOptEl && jfOptEl.hide();
  264. jfPathEl && jfPathEl.hide();
  265. });
  266. buttonCollapseAll.bind('click', function (e) {
  267. // 如果内容还没有格式化过,需要再格式化一下
  268. if (plainOn) {
  269. buttonFormatted.trigger('click');
  270. }
  271. if (buttonCollapseAll.text() === '折叠所有') {
  272. buttonCollapseAll.text('展开所有');
  273. collapse($('.objProp,.arrElem'));
  274. } else {
  275. buttonCollapseAll.text('折叠所有');
  276. $('.objProp,.arrElem').removeClass('collapsed');
  277. }
  278. jfOptEl && jfOptEl.hide();
  279. jfPathEl && jfPathEl.hide();
  280. });
  281. };
  282. // 显示当前节点的Key
  283. let _showJsonKey = function (curEl) {
  284. let keys = [];
  285. do {
  286. if (curEl.hasClass('arrElem')) {
  287. if (!curEl.hasClass('rootKvov')) {
  288. keys.unshift('[' + curEl.prevAll('.kvov').length + ']');
  289. }
  290. } else {
  291. keys.unshift(curEl.find('>.k').text());
  292. }
  293. if(curEl.parent().hasClass('rootKvov') || curEl.parent().parent().hasClass('rootKvov')) {
  294. break;
  295. }
  296. curEl = curEl.parent().parent();
  297. } while (curEl.length && !curEl.hasClass('rootKvov'));
  298. let path = keys.join('#@#').replace(/#@#\[/g, '[').replace(/#@#/g, '.');
  299. if (!jfPathEl) {
  300. jfPathEl = $('<div/>').css({
  301. position: 'fixed',
  302. bottom: 0,
  303. left: 0,
  304. background: 'rgb(0, 0, 0,0.6)',
  305. color: '#ff0',
  306. fontSize: '12px',
  307. fontWeight: 'bold',
  308. padding: '2px 10px 2px 2px'
  309. }).appendTo('body');
  310. }
  311. jfPathEl.html('当前路径:' + path).show();
  312. };
  313. // 附加操作
  314. let _addEvents = function () {
  315. // 折叠、展开
  316. $('#jfContent span.e').bind('click', function (ev) {
  317. ev.preventDefault();
  318. let parentEl = $(this).parent();
  319. parentEl.toggleClass('collapsed');
  320. if (parentEl.hasClass('collapsed')) {
  321. collapse(parentEl);
  322. }
  323. });
  324. // 点击选中:高亮
  325. $('#jfContent .kvov').bind('click', function (e) {
  326. if ($(this).hasClass('x-outline')) {
  327. jfOptEl && jfOptEl.hide();
  328. jfPathEl && jfPathEl.hide();
  329. $(this).removeClass('x-outline');
  330. e.stopPropagation();
  331. return true;
  332. }
  333. $('.x-outline').removeClass('x-outline');
  334. let el = $(this).removeClass('x-hover').addClass('x-outline');
  335. // 增加复制、删除功能
  336. _addOptForItem(el);
  337. // 显示key
  338. _showJsonKey(el);
  339. if (!$(e.target).is('.kvov .e')) {
  340. e.stopPropagation();
  341. } else {
  342. $(e.target).parent().trigger('click');
  343. }
  344. // 触发钩子
  345. if (typeof window._OnJsonItemClickByFH === 'function') {
  346. window._OnJsonItemClickByFH(getJsonText(el));
  347. }
  348. }).bind('mouseover', function (e) {
  349. $(this).addClass('x-hover');
  350. return false;
  351. }).bind('mouseout', function (e) {
  352. $(this).removeClass('x-hover');
  353. });
  354. };
  355. return {
  356. format: format,
  357. postMessage: postMessage
  358. }
  359. })();
  360. let JsonFormatDealer = (function () {
  361. "use strict";
  362. // Constants
  363. let
  364. TYPE_STRING = 1,
  365. TYPE_NUMBER = 2,
  366. TYPE_OBJECT = 3,
  367. TYPE_ARRAY = 4,
  368. TYPE_BOOL = 5,
  369. TYPE_NULL = 6
  370. ;
  371. // Utility functions
  372. function removeComments(str) {
  373. str = ('__' + str + '__').split('');
  374. let mode = {
  375. singleQuote: false,
  376. doubleQuote: false,
  377. regex: false,
  378. blockComment: false,
  379. lineComment: false,
  380. condComp: false
  381. };
  382. for (let i = 0, l = str.length; i < l; i++) {
  383. if (mode.regex) {
  384. if (str[i] === '/' && str[i - 1] !== '\\') {
  385. mode.regex = false;
  386. }
  387. continue;
  388. }
  389. if (mode.singleQuote) {
  390. if (str[i] === "'" && str[i - 1] !== '\\') {
  391. mode.singleQuote = false;
  392. }
  393. continue;
  394. }
  395. if (mode.doubleQuote) {
  396. if (str[i] === '"' && str[i - 1] !== '\\') {
  397. mode.doubleQuote = false;
  398. }
  399. continue;
  400. }
  401. if (mode.blockComment) {
  402. if (str[i] === '*' && str[i + 1] === '/') {
  403. str[i + 1] = '';
  404. mode.blockComment = false;
  405. }
  406. str[i] = '';
  407. continue;
  408. }
  409. if (mode.lineComment) {
  410. if (str[i + 1] === '\n' || str[i + 1] === '\r') {
  411. mode.lineComment = false;
  412. }
  413. str[i] = '';
  414. continue;
  415. }
  416. if (mode.condComp) {
  417. if (str[i - 2] === '@' && str[i - 1] === '*' && str[i] === '/') {
  418. mode.condComp = false;
  419. }
  420. continue;
  421. }
  422. mode.doubleQuote = str[i] === '"';
  423. mode.singleQuote = str[i] === "'";
  424. if (str[i] === '/') {
  425. if (str[i + 1] === '*' && str[i + 2] === '@') {
  426. mode.condComp = true;
  427. continue;
  428. }
  429. if (str[i + 1] === '*') {
  430. str[i] = '';
  431. mode.blockComment = true;
  432. continue;
  433. }
  434. if (str[i + 1] === '/') {
  435. str[i] = '';
  436. mode.lineComment = true;
  437. continue;
  438. }
  439. mode.regex = true;
  440. }
  441. }
  442. return str.join('').slice(2, -2);
  443. }
  444. // Template elements
  445. let templates,
  446. baseDiv = document.createElement('div'),
  447. baseSpan = document.createElement('span');
  448. function getSpanBoth(innerText, className) {
  449. let span = baseSpan.cloneNode(false);
  450. span.className = className;
  451. span.innerText = innerText;
  452. return span;
  453. }
  454. function getSpanText(innerText) {
  455. let span = baseSpan.cloneNode(false);
  456. span.innerText = innerText;
  457. return span;
  458. }
  459. function getSpanClass(className) {
  460. let span = baseSpan.cloneNode(false);
  461. span.className = className;
  462. return span;
  463. }
  464. function getDivClass(className) {
  465. let span = baseDiv.cloneNode(false);
  466. span.className = className;
  467. return span;
  468. }
  469. // Create template nodes
  470. let templatesObj = {
  471. t_kvov: getDivClass('kvov'),
  472. t_key: getSpanClass('k'),
  473. t_string: getSpanClass('s'),
  474. t_number: getSpanClass('n'),
  475. t_exp: getSpanClass('e'),
  476. t_null: getSpanBoth('null', 'nl'),
  477. t_true: getSpanBoth('true', 'bl'),
  478. t_false: getSpanBoth('false', 'bl'),
  479. t_oBrace: getSpanBoth('{', 'b'),
  480. t_cBrace: getSpanBoth('}', 'b'),
  481. t_oBracket: getSpanBoth('[', 'b'),
  482. t_cBracket: getSpanBoth(']', 'b'),
  483. t_ellipsis: getSpanClass('ell'),
  484. t_blockInner: getSpanClass('blockInner'),
  485. t_colonAndSpace: document.createTextNode(':\u00A0'),
  486. t_commaText: document.createTextNode(','),
  487. t_dblqText: document.createTextNode('"')
  488. };
  489. // Core recursive DOM-building function
  490. function getKvovDOM(value, keyName) {
  491. let type,
  492. kvov,
  493. nonZeroSize,
  494. templates = templatesObj, // bring into scope for tiny speed boost
  495. objKey,
  496. keySpan,
  497. valueElement
  498. ;
  499. // Establish value type
  500. if (typeof value === 'string')
  501. type = TYPE_STRING;
  502. else if (typeof value === 'number')
  503. type = TYPE_NUMBER;
  504. else if (value === false || value === true)
  505. type = TYPE_BOOL;
  506. else if (value === null)
  507. type = TYPE_NULL;
  508. else if (value instanceof Array)
  509. type = TYPE_ARRAY;
  510. else
  511. type = TYPE_OBJECT;
  512. // Root node for this kvov
  513. kvov = templates.t_kvov.cloneNode(false);
  514. // Add an 'expander' first (if this is object/array with non-zero size)
  515. if (type === TYPE_OBJECT || type === TYPE_ARRAY) {
  516. if (typeof JSON.BigNumber === 'function' && value instanceof JSON.BigNumber) {
  517. value = JSON.stringify(value);
  518. type = TYPE_NUMBER;
  519. } else {
  520. nonZeroSize = false;
  521. for (objKey in value) {
  522. if (value.hasOwnProperty(objKey)) {
  523. nonZeroSize = true;
  524. break; // no need to keep counting; only need one
  525. }
  526. }
  527. if (nonZeroSize)
  528. kvov.appendChild(templates.t_exp.cloneNode(true));
  529. }
  530. }
  531. // If there's a key, add that before the value
  532. if (keyName !== false) { // NB: "" is a legal keyname in JSON
  533. // This kvov must be an object property
  534. kvov.classList.add('objProp');
  535. // Create a span for the key name
  536. keySpan = templates.t_key.cloneNode(false);
  537. keySpan.textContent = JSON.stringify(keyName).slice(1, -1); // remove quotes
  538. // Add it to kvov, with quote marks
  539. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  540. kvov.appendChild(keySpan);
  541. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  542. // Also add ":&nbsp;" (colon and non-breaking space)
  543. kvov.appendChild(templates.t_colonAndSpace.cloneNode(false));
  544. }
  545. else {
  546. // This is an array element instead
  547. kvov.classList.add('arrElem');
  548. }
  549. // Generate DOM for this value
  550. let blockInner, childKvov;
  551. switch (type) {
  552. case TYPE_STRING:
  553. // If string is a URL, get a link, otherwise get a span
  554. let innerStringEl = baseSpan.cloneNode(false),
  555. escapedString = JSON.stringify(value);
  556. escapedString = escapedString.substring(1, escapedString.length - 1); // remove quotes
  557. if (value[0] === 'h' && value.substring(0, 4) === 'http') { // crude but fast - some false positives, but rare, and UX doesn't suffer terribly from them.
  558. let innerStringA = document.createElement('A');
  559. innerStringA.href = value;
  560. innerStringA.innerText = escapedString;
  561. innerStringEl.appendChild(innerStringA);
  562. }
  563. else {
  564. innerStringEl.innerText = escapedString;
  565. }
  566. valueElement = templates.t_string.cloneNode(false);
  567. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  568. valueElement.appendChild(innerStringEl);
  569. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  570. kvov.appendChild(valueElement);
  571. break;
  572. case TYPE_NUMBER:
  573. // Simply add a number element (span.n)
  574. valueElement = templates.t_number.cloneNode(false);
  575. valueElement.innerText = value;
  576. kvov.appendChild(valueElement);
  577. break;
  578. case TYPE_OBJECT:
  579. // Add opening brace
  580. kvov.appendChild(templates.t_oBrace.cloneNode(true));
  581. // If any properties, add a blockInner containing k/v pair(s)
  582. if (nonZeroSize) {
  583. // Add ellipsis (empty, but will be made to do something when kvov is collapsed)
  584. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  585. // Create blockInner, which indents (don't attach yet)
  586. blockInner = templates.t_blockInner.cloneNode(false);
  587. // For each key/value pair, add as a kvov to blockInner
  588. let count = 0, k, comma;
  589. for (k in value) {
  590. if (value.hasOwnProperty(k)) {
  591. count++;
  592. childKvov = getKvovDOM(value[k], k);
  593. // Add comma
  594. comma = templates.t_commaText.cloneNode();
  595. childKvov.appendChild(comma);
  596. blockInner.appendChild(childKvov);
  597. }
  598. }
  599. // Now remove the last comma
  600. childKvov.removeChild(comma);
  601. // Add blockInner
  602. kvov.appendChild(blockInner);
  603. }
  604. // Add closing brace
  605. kvov.appendChild(templates.t_cBrace.cloneNode(true));
  606. break;
  607. case TYPE_ARRAY:
  608. // Add opening bracket
  609. kvov.appendChild(templates.t_oBracket.cloneNode(true));
  610. // If non-zero length array, add blockInner containing inner vals
  611. if (nonZeroSize) {
  612. // Add ellipsis
  613. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  614. // Create blockInner (which indents) (don't attach yet)
  615. blockInner = templates.t_blockInner.cloneNode(false);
  616. // For each key/value pair, add the markup
  617. for (let i = 0, length = value.length, lastIndex = length - 1; i < length; i++) {
  618. // Make a new kvov, with no key
  619. childKvov = getKvovDOM(value[i], false);
  620. // Add comma if not last one
  621. if (i < lastIndex)
  622. childKvov.appendChild(templates.t_commaText.cloneNode());
  623. // Append the child kvov
  624. blockInner.appendChild(childKvov);
  625. }
  626. // Add blockInner
  627. kvov.appendChild(blockInner);
  628. }
  629. // Add closing bracket
  630. kvov.appendChild(templates.t_cBracket.cloneNode(true));
  631. break;
  632. case TYPE_BOOL:
  633. if (value)
  634. kvov.appendChild(templates.t_true.cloneNode(true));
  635. else
  636. kvov.appendChild(templates.t_false.cloneNode(true));
  637. break;
  638. case TYPE_NULL:
  639. kvov.appendChild(templates.t_null.cloneNode(true));
  640. break;
  641. }
  642. return kvov;
  643. }
  644. // Function to convert object to an HTML string
  645. function jsonObjToHTML(obj, jsonpFunctionName) {
  646. // spin(5) ;
  647. // Format object (using recursive kvov builder)
  648. let rootKvov = getKvovDOM(obj, false);
  649. // The whole DOM is now built.
  650. // Set class on root node to identify it
  651. rootKvov.classList.add('rootKvov');
  652. // Make div#formattedJson and append the root kvov
  653. let divFormattedJson = document.createElement('DIV');
  654. divFormattedJson.id = 'formattedJson';
  655. divFormattedJson.appendChild(rootKvov);
  656. // Convert it to an HTML string (shame about this step, but necessary for passing it through to the content page)
  657. let returnHTML = divFormattedJson.outerHTML;
  658. // Top and tail with JSONP padding if necessary
  659. if (jsonpFunctionName !== null) {
  660. returnHTML =
  661. '<div id="jsonpOpener">' + jsonpFunctionName + ' ( </div>' +
  662. returnHTML +
  663. '<div id="jsonpCloser">)</div>';
  664. }
  665. // Return the HTML
  666. return returnHTML;
  667. }
  668. // Listen for requests from content pages wanting to set up a port
  669. let postMessage = function (msg) {
  670. let jsonpFunctionName = null;
  671. if (msg.type === 'SENDING TEXT') {
  672. // Try to parse as JSON
  673. let obj,
  674. text = msg.text;
  675. try {
  676. obj = JSON.parse(text);
  677. }
  678. catch (e) {
  679. // Not JSON; could be JSONP though.
  680. // Try stripping 'padding' (if any), and try parsing it again
  681. text = text.trim();
  682. // Find where the first paren is (and exit if none)
  683. let indexOfParen;
  684. if (!(indexOfParen = text.indexOf('('))) {
  685. JsonFormatEntrance.postMessage(['NOT JSON', 'no opening parenthesis']);
  686. return;
  687. }
  688. // Get the substring up to the first "(", with any comments/whitespace stripped out
  689. let firstBit = removeComments(text.substring(0, indexOfParen)).trim();
  690. if (!firstBit.match(/^[a-zA-Z_$][\.\[\]'"0-9a-zA-Z_$]*$/)) {
  691. // The 'firstBit' is NOT a valid function identifier.
  692. JsonFormatEntrance.postMessage(['NOT JSON', 'first bit not a valid function name']);
  693. return;
  694. }
  695. // Find last parenthesis (exit if none)
  696. let indexOfLastParen;
  697. if (!(indexOfLastParen = text.lastIndexOf(')'))) {
  698. JsonFormatEntrance.postMessage(['NOT JSON', 'no closing paren']);
  699. return;
  700. }
  701. // Check that what's after the last parenthesis is just whitespace, comments, and possibly a semicolon (exit if anything else)
  702. let lastBit = removeComments(text.substring(indexOfLastParen + 1)).trim();
  703. if (lastBit !== "" && lastBit !== ';') {
  704. JsonFormatEntrance.postMessage(['NOT JSON', 'last closing paren followed by invalid characters']);
  705. return;
  706. }
  707. // So, it looks like a valid JS function call, but we don't know whether it's JSON inside the parentheses...
  708. // Check if the 'argument' is actually JSON (and record the parsed result)
  709. text = text.substring(indexOfParen + 1, indexOfLastParen);
  710. try {
  711. obj = JSON.parse(text);
  712. }
  713. catch (e2) {
  714. // Just some other text that happens to be in a function call.
  715. // Respond as not JSON, and exit
  716. JsonFormatEntrance.postMessage(['NOT JSON', 'looks like a function call, but the parameter is not valid JSON']);
  717. return;
  718. }
  719. jsonpFunctionName = firstBit;
  720. }
  721. // If still running, we now have obj, which is valid JSON.
  722. // Ensure it's not a number or string (technically valid JSON, but no point prettifying it)
  723. if (typeof obj !== 'object' && typeof obj !== 'array') {
  724. JsonFormatEntrance.postMessage(['NOT JSON', 'technically JSON but not an object or array']);
  725. return;
  726. }
  727. JsonFormatEntrance.postMessage(['FORMATTING']);
  728. try {
  729. // 有的页面设置了 安全策略,连localStorage都不能用,setTimeout开启多线程就更别说了
  730. localStorage.getItem('just test : Blocked script execution in xxx?');
  731. // 在非UI线程中操作:异步。。。
  732. setTimeout(function () {
  733. // Do formatting
  734. let html = jsonObjToHTML(obj, jsonpFunctionName);
  735. // Post the HTML string to the content script
  736. JsonFormatEntrance.postMessage(['FORMATTED', html]);
  737. }, 0);
  738. } catch (ex) {
  739. // 错误信息类似:Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
  740. let html = jsonObjToHTML(obj, jsonpFunctionName);
  741. JsonFormatEntrance.postMessage(['FORMATTED', html]);
  742. }
  743. }
  744. };
  745. return {
  746. postMessage: postMessage
  747. };
  748. })();
  749. module.exports = {
  750. format: JsonFormatEntrance.format
  751. };