contentscript-jsonformat.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /**
  2. * content_scripts中如果被检测到当前页面内容为json数据,则自动进行JSON格式化
  3. */
  4. baidu.csJsonFormat = (function () {
  5. "use strict";
  6. var _htmlFragment = [
  7. '<div class="mod-json mod-contentscript"><div class="rst-item">',
  8. '<div id="formattingMsg">',
  9. '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">',
  10. '<path d="M 150,0 a 150,150 0 0,1 106.066,256.066 l -35.355,-35.355 a -100,-100 0 0,0 -70.711,-170.711 z" fill="#3d7fe6"></path>',
  11. '</svg>加载中...',
  12. '</div>',
  13. '<div id="jfCallbackName_start" class="callback-name"></div>',
  14. '<div id="jfContent"></div>',
  15. '<pre id="jfContent_pre"></pre>',
  16. '<div id="jfCallbackName_end" class="callback-name"></div>',
  17. '</div></div>'
  18. ].join('');
  19. var _loadCss = function () {
  20. var fcpCss = chrome.extension.getURL('static/css/fe-jsonformat-content.css');
  21. jQuery('<link id="_fehelper_fcp_css_" href="' + fcpCss + '" rel="stylesheet" type="text/css" />').appendTo('head');
  22. };
  23. /**
  24. * 从页面提取JSON文本
  25. * @return {*}
  26. * @private
  27. */
  28. var _getJsonText = function () {
  29. var pre = $('body>pre:eq(0)')[0] || {textContent: ""};
  30. var source = $.trim(pre.textContent);
  31. if (!source) {
  32. source = $.trim(document.body.textContent || '')
  33. }
  34. if (!source) {
  35. return false;
  36. }
  37. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  38. // 如果是合法的json,也只可能有一个text节点
  39. var nodes = document.body.childNodes;
  40. var newSource = '';
  41. for (var i = 0, len = nodes.length; i < len; i++) {
  42. if (nodes[i].nodeType == Node.TEXT_NODE) {
  43. newSource += nodes[i].textContent;
  44. } else if (nodes[i].nodeType == Node.ELEMENT_NODE) {
  45. var tagName = nodes[i].tagName.toLowerCase();
  46. var html = $.trim(nodes[i].textContent);
  47. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  48. if (tagName === 'pre' && html === source) {
  49. continue;
  50. } else if (nodes[i].offsetWidth === 0 || nodes[i].offsetHeight === 0 || !html) {
  51. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  52. continue;
  53. } else {
  54. return false;
  55. }
  56. } else {
  57. return false;
  58. }
  59. }
  60. return newSource || source;
  61. };
  62. /**
  63. * 此方法用于将Unicode码解码为正常字符串
  64. * @param {Object} text
  65. */
  66. var _uniDecode = function (text) {
  67. text = text.replace(/\\/g, "%").replace('%U','%u').replace('%u0025', '%25');
  68. text = unescape(text.toString().replace(/%2B/g, "+"));
  69. var matches = text.match(/(%u00([0-9A-F]{2}))/gi);
  70. if (matches) {
  71. for (var matchid = 0; matchid < matches.length; matchid++) {
  72. var code = matches[matchid].substring(1, 3);
  73. var x = Number("0x" + code);
  74. if (x >= 128) {
  75. text = text.replace(matches[matchid], code);
  76. }
  77. }
  78. }
  79. text = unescape(text.toString().replace(/%2B/g, "+"));
  80. return text;
  81. };
  82. /**
  83. * 执行format操作
  84. * @private
  85. */
  86. var _format = function () {
  87. var source = _getJsonText();
  88. if (!source) {
  89. return;
  90. }
  91. // JSONP形式下的callback name
  92. var funcName = null;
  93. // json对象
  94. var jsonObj = null;
  95. var newSource = '';
  96. // 下面校验给定字符串是否为一个合法的json
  97. try {
  98. // 再看看是不是jsonp的格式
  99. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  100. var matches = reg.exec(source);
  101. if (matches != null) {
  102. funcName = matches[1];
  103. newSource = matches[2];
  104. jsonObj = new Function("return " + newSource)();
  105. }
  106. } catch (ex) {
  107. return;
  108. }
  109. try {
  110. if (jsonObj == null || typeof jsonObj != 'object') {
  111. jsonObj = new Function("return " + source)();
  112. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  113. if (typeof jsonObj == "string") {
  114. // 再来一次
  115. jsonObj = new Function("return " + jsonObj)();
  116. }
  117. }
  118. } catch (e) {
  119. return;
  120. }
  121. // 是json格式,可以进行JSON自动格式化
  122. if (jsonObj != null && typeof jsonObj == "object") {
  123. try {
  124. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  125. newSource = JSON.stringify(jsonObj);
  126. // 如果newSource的长度比原source长度短很多的话,猜测应该是格式化错了,需要撤销操作
  127. // 这里一定要unicode decode一下,要不然会出现误判
  128. if(newSource.length * 2 < (_uniDecode(source)).length) {
  129. return ;
  130. }
  131. // 直接replace掉所有\w之外的字符,再和原内容比较
  132. var r_ns = newSource.replace(/[^\w]/gm,'').length;
  133. var r_os = _uniDecode(source).replace(/[^\w]/gm,'').length;
  134. // 允许内容产生1%的误差
  135. if(Math.abs(r_ns - r_os) > (r_ns + r_os) / 200) {
  136. return ;
  137. }
  138. } catch (ex) {
  139. // 通过JSON反解不出来的,一定有问题
  140. return;
  141. }
  142. $('body').html(_htmlFragment);
  143. _loadCss();
  144. // 点击区块高亮
  145. $('#jfContent').delegate('.kvov', 'click', function (e) {
  146. $('#jfContent .kvov').removeClass('x-outline');
  147. $(this).removeClass('x-hover').addClass('x-outline');
  148. if (!$(e.target).is('.kvov .e')) {
  149. e.stopPropagation();
  150. } else {
  151. $(e.target).parent().trigger('click');
  152. }
  153. }).delegate('.kvov', 'mouseover', function (e) {
  154. $(this).addClass('x-hover');
  155. return false;
  156. }).delegate('.kvov', 'mouseout', function (e) {
  157. $(this).removeClass('x-hover');
  158. });
  159. JsonFormatEntrance.clear();
  160. JsonFormatEntrance.format(newSource);
  161. // 如果是JSONP格式的,需要把方法名也显示出来
  162. if (funcName != null) {
  163. $('#jfCallbackName_start').html(funcName + '(');
  164. $('#jfCallbackName_end').html(')');
  165. }
  166. }
  167. };
  168. var _init = function () {
  169. $(function () {
  170. if (!/^filesystem\:/.test(location.href)) {
  171. _format();
  172. }
  173. });
  174. };
  175. return {
  176. init: _init
  177. };
  178. })();
  179. baidu.csJsonFormat.init();