fe-jsonformat.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * JSON格式化
  3. */
  4. baidu.jsonformat = (function () {
  5. "use strict";
  6. /**
  7. * chrome 下复制到剪贴板
  8. * @param text
  9. */
  10. var _copyToClipboard = function(text) {
  11. const input = document.createElement('textarea');
  12. input.style.position = 'fixed';
  13. input.style.opacity = 0;
  14. input.value = text;
  15. document.body.appendChild(input);
  16. input.select();
  17. document.execCommand('Copy');
  18. document.body.removeChild(input);
  19. alert('Json片段复制成功,随处粘贴可用!')
  20. };
  21. /**
  22. * 给某个节点增加操作项
  23. * @param el
  24. * @private
  25. */
  26. var _addOptForItem = function(el){
  27. // 复制json片段
  28. var fnCopy = function (ec) {
  29. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  30. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  31. txt = '{' + txt + '}';
  32. }
  33. try {
  34. txt = JSON.stringify(JSON.parse(txt), null, 4);
  35. } catch (err) {
  36. }
  37. _copyToClipboard(txt);
  38. };
  39. // 删除json片段
  40. var fnDel = function (ed) {
  41. if (el.parent().is('#formattedJson')) {
  42. alert('如果连最外层的Json也删掉的话,就没啥意义了哦!');
  43. return false;
  44. }
  45. el.remove();
  46. boxOpt.css('top', -1000);
  47. };
  48. var boxOpt = $('#boxOpt');
  49. if (!boxOpt.length) {
  50. boxOpt = $('<div id="boxOpt"><a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  51. }
  52. boxOpt.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  53. boxOpt.find('a.opt-del').unbind('click').bind('click', fnDel);
  54. boxOpt.css({
  55. left: el.offset().left + el.width() - 50,
  56. top: el.offset().top
  57. });
  58. };
  59. /**
  60. * 执行format操作
  61. * @private
  62. */
  63. var _format = function () {
  64. $('#errorMsg').html('');
  65. $('#modJsonResult').hide();
  66. var source = $('#jsonSource').val().replace(/\n/gm,' ');
  67. if (!source) {
  68. return;
  69. }
  70. // JSONP形式下的callback name
  71. var funcName = null;
  72. // json对象
  73. var jsonObj = null;
  74. // 下面校验给定字符串是否为一个合法的json
  75. try {
  76. // 再看看是不是jsonp的格式
  77. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  78. var matches = reg.exec(source);
  79. if (matches != null) {
  80. funcName = matches[1];
  81. var newSource = matches[2];
  82. jsonObj = new Function("return " + newSource)();
  83. }
  84. } catch (ex) {
  85. $('#errorMsg').html(ex.message);
  86. return;
  87. }
  88. try {
  89. if (jsonObj == null || typeof jsonObj != 'object') {
  90. jsonObj = new Function("return " + source)();
  91. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  92. if (typeof jsonObj == "string") {
  93. // 再来一次
  94. jsonObj = new Function("return " + jsonObj)();
  95. }
  96. }
  97. } catch (ex) {
  98. $('#errorMsg').html(ex.message);
  99. return;
  100. }
  101. // 是json格式,可以进行JSON自动格式化
  102. if (jsonObj != null && typeof jsonObj == "object") {
  103. try {
  104. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  105. source = JSON.stringify(jsonObj);
  106. } catch (ex) {
  107. // 通过JSON反解不出来的,一定有问题
  108. return;
  109. }
  110. JsonFormatEntrance.clear();
  111. JsonFormatEntrance.format(source);
  112. $('#modJsonResult').show();
  113. // 如果是JSONP格式的,需要把方法名也显示出来
  114. if (funcName != null) {
  115. $('#jfCallbackName_start').html(funcName + '(');
  116. $('#jfCallbackName_end').html(')');
  117. }
  118. }
  119. };
  120. /**
  121. * 事件绑定
  122. * @private
  123. */
  124. var _bindEvents = function () {
  125. $('#btnFormat').click(function (e) {
  126. _format();
  127. });
  128. // 点击区块高亮
  129. $('#jfContent').delegate('.kvov', 'click', function (e) {
  130. $('#jfContent .kvov').removeClass('x-outline');
  131. var el = $(this).removeClass('x-hover').addClass('x-outline');
  132. // 增加复制、删除功能
  133. _addOptForItem(el);
  134. if (!$(e.target).is('.kvov .e')) {
  135. e.stopPropagation();
  136. } else {
  137. $(e.target).parent().trigger('click');
  138. }
  139. }).delegate('.kvov', 'mouseover', function (e) {
  140. $(this).addClass('x-hover');
  141. return false;
  142. }).delegate('.kvov', 'mouseout', function (e) {
  143. $(this).removeClass('x-hover');
  144. });
  145. };
  146. var _init = function () {
  147. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  148. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  149. if (request.type == MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event == 'jsonformat') {
  150. if (request.content) {
  151. document.getElementById('jsonSource').value = (request.content);
  152. _format();
  153. }
  154. }
  155. });
  156. $(function () {
  157. //输入框聚焦
  158. jQuery("#jsonSource").focus();
  159. _bindEvents();
  160. });
  161. };
  162. return {
  163. init: _init
  164. };
  165. })();
  166. baidu.jsonformat.init();