fe-jsonformat.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /**
  2. * JSON格式化
  3. */
  4. baidu.jsonformat = (function () {
  5. "use strict";
  6. /**
  7. * chrome 下复制到剪贴板
  8. * @param text
  9. */
  10. var _copyToClipboard = function (text) {
  11. var 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. alert('节点已删除成功!');
  47. boxOpt.css('top', -1000).hide();
  48. };
  49. var boxOpt = $('#boxOpt');
  50. if (!boxOpt.length) {
  51. boxOpt = $('<div id="boxOpt"><a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  52. }
  53. boxOpt.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  54. boxOpt.find('a.opt-del').unbind('click').bind('click', fnDel);
  55. boxOpt.css({
  56. left: el.offset().left + el.width() - 50,
  57. top: el.offset().top
  58. }).show();
  59. };
  60. /**
  61. * 执行format操作
  62. * @private
  63. */
  64. var _format = function () {
  65. $('#boxOpt').remove();
  66. $('#errorMsg').html('');
  67. $('#modJsonResult').show().find('#jfContent').html(placeholder);
  68. var source = $('#jsonSource').val().replace(/\n/gm, ' ');
  69. if (!source) {
  70. return;
  71. }
  72. // JSONP形式下的callback name
  73. var funcName = null;
  74. // json对象
  75. var jsonObj = null;
  76. // 下面校验给定字符串是否为一个合法的json
  77. try {
  78. // 再看看是不是jsonp的格式
  79. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  80. var matches = reg.exec(source);
  81. if (matches != null) {
  82. funcName = matches[1];
  83. var newSource = matches[2];
  84. jsonObj = new Function("return " + newSource)();
  85. }
  86. } catch (ex) {
  87. $('#errorMsg').html(ex.message);
  88. return;
  89. }
  90. try {
  91. if (jsonObj == null || typeof jsonObj != 'object') {
  92. jsonObj = new Function("return " + source)();
  93. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  94. if (typeof jsonObj == "string") {
  95. // 再来一次
  96. jsonObj = new Function("return " + jsonObj)();
  97. }
  98. }
  99. } catch (ex) {
  100. $('#errorMsg').html(ex.message);
  101. return;
  102. }
  103. // 是json格式,可以进行JSON自动格式化
  104. if (jsonObj != null && typeof jsonObj == "object") {
  105. try {
  106. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  107. source = JSON.stringify(jsonObj);
  108. } catch (ex) {
  109. // 通过JSON反解不出来的,一定有问题
  110. return;
  111. }
  112. JsonFormatEntrance.clear();
  113. JsonFormatEntrance.format(source);
  114. $('#modJsonResult').show();
  115. // 如果是JSONP格式的,需要把方法名也显示出来
  116. if (funcName != null) {
  117. $('#jfCallbackName_start').html(funcName + '(');
  118. $('#jfCallbackName_end').html(')');
  119. }
  120. }
  121. };
  122. /**
  123. * 事件绑定
  124. * @private
  125. */
  126. var _bindEvents = function () {
  127. $('#btnFormat').click(function (e) {
  128. _format();
  129. });
  130. // 点击区块高亮
  131. $('#jfContent').delegate('.kvov', 'click', function (e) {
  132. if ($(this).hasClass('x-outline')) {
  133. $('#boxOpt').remove();
  134. $(this).removeClass('x-outline');
  135. return false;
  136. }
  137. $('#jfContent .kvov').removeClass('x-outline');
  138. var el = $(this).removeClass('x-hover').addClass('x-outline');
  139. // 增加复制、删除功能
  140. _addOptForItem(el);
  141. if (!$(e.target).is('.kvov .e')) {
  142. e.stopPropagation();
  143. } else {
  144. $(e.target).parent().trigger('click');
  145. }
  146. }).delegate('.kvov', 'mouseover', function (e) {
  147. $(this).addClass('x-hover');
  148. return false;
  149. }).delegate('.kvov', 'mouseout', function (e) {
  150. $(this).removeClass('x-hover');
  151. });
  152. $('.mod-json').click(function (e) {
  153. if ($.contains('#jfContent', e.target)) {
  154. $('#boxOpt').remove();
  155. $('.x-outline').removeClass('x-outline')
  156. }
  157. });
  158. $('span.x-xdemo').click(function (e) {
  159. $('#jsonSource').val($('#demo').val()).focus()
  160. });
  161. };
  162. var placeholder = '';
  163. var _init = function () {
  164. $(function () {
  165. placeholder = $('#jfContent').html();
  166. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  167. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  168. if (request.type == MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event == 'jsonformat') {
  169. if (request.content) {
  170. document.getElementById('jsonSource').value = (request.content);
  171. _format();
  172. }
  173. }
  174. });
  175. //输入框聚焦
  176. jQuery("#jsonSource").focus();
  177. _bindEvents();
  178. });
  179. };
  180. return {
  181. init: _init
  182. };
  183. })();
  184. baidu.jsonformat.init();