contentscript-jsonformat.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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="formatTips">本页JSON数据由FeHelper进行自动格式化,若有任何问题,点击这里提交 ',
  9. '<a href="http://www.baidufe.com/item/889639af23968ee688b9.html#comment" target="_blank">意见反馈</a>',
  10. '</div>',
  11. '<div id="formattingMsg">',
  12. '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">',
  13. '<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>',
  14. '</svg>加载中...',
  15. '</div>',
  16. '<div id="jfCallbackName_start" class="callback-name"></div>',
  17. '<div id="jfContent"></div>',
  18. '<pre id="jfContent_pre"></pre>',
  19. '<div id="jfCallbackName_end" class="callback-name"></div>',
  20. '</div></div>'
  21. ].join('');
  22. var _loadCss = function () {
  23. var fcpCss = chrome.extension.getURL('static/css/fe-jsonformat.css');
  24. jQuery('<link id="_fehelper_fcp_css_" href="' + fcpCss + '" rel="stylesheet" type="text/css" />').appendTo('head');
  25. };
  26. /**
  27. * 从页面提取JSON文本
  28. * @return {*}
  29. * @private
  30. */
  31. var _getJsonText = function () {
  32. var pre = $('body>pre:eq(0)')[0] || {textContent: ""};
  33. var source = $.trim(pre.textContent);
  34. if (!source) {
  35. source = $.trim(document.body.textContent || '')
  36. }
  37. if (!source) {
  38. return false;
  39. }
  40. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  41. // 如果是合法的json,也只可能有一个text节点
  42. var nodes = document.body.childNodes;
  43. var newSource = '';
  44. for (var i = 0, len = nodes.length; i < len; i++) {
  45. if (nodes[i].nodeType == Node.TEXT_NODE) {
  46. newSource += nodes[i].textContent;
  47. } else if (nodes[i].nodeType == Node.ELEMENT_NODE) {
  48. var tagName = nodes[i].tagName.toLowerCase();
  49. var html = $.trim(nodes[i].textContent);
  50. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  51. if (tagName === 'pre' && html === source) {
  52. continue;
  53. } else if (tagName === 'embed' && nodes[i].offsetWidth === 0) {
  54. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  55. continue;
  56. } else {
  57. return false;
  58. }
  59. } else {
  60. return false;
  61. }
  62. }
  63. return newSource || source;
  64. };
  65. /**
  66. * 执行format操作
  67. * @private
  68. */
  69. var _format = function () {
  70. var source = _getJsonText();
  71. if (!source) {
  72. return;
  73. }
  74. // JSONP形式下的callback name
  75. var funcName = null;
  76. // json对象
  77. var jsonObj = null;
  78. var newSource = '';
  79. // 下面校验给定字符串是否为一个合法的json
  80. try {
  81. // 再看看是不是jsonp的格式
  82. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  83. var matches = reg.exec(source);
  84. if (matches != null) {
  85. funcName = matches[1];
  86. newSource = matches[2];
  87. jsonObj = new Function("return " + newSource)();
  88. }
  89. } catch (ex) {
  90. return;
  91. }
  92. try {
  93. if (jsonObj == null || typeof jsonObj != 'object') {
  94. jsonObj = new Function("return " + source)();
  95. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  96. if (typeof jsonObj == "string") {
  97. // 再来一次
  98. jsonObj = new Function("return " + jsonObj)();
  99. }
  100. }
  101. } catch (e) {
  102. return;
  103. }
  104. // 是json格式,可以进行JSON自动格式化
  105. if (jsonObj != null && typeof jsonObj == "object") {
  106. try {
  107. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  108. newSource = JSON.stringify(jsonObj);
  109. // 如果newSource的长度比原source长度短很多的话,猜测应该是格式化错了,需要撤销操作
  110. if(newSource.length * 2 < source.length) {
  111. return ;
  112. }
  113. } catch (ex) {
  114. // 通过JSON反解不出来的,一定有问题
  115. return;
  116. }
  117. $('body').html(_htmlFragment);
  118. _loadCss();
  119. // 点击区块高亮
  120. $('#jfContent').delegate('.kvov', 'click', function (e) {
  121. $('#jfContent .kvov').removeClass('x-outline');
  122. $(this).removeClass('x-hover').addClass('x-outline');
  123. if (!$(e.target).is('.kvov .e')) {
  124. e.stopPropagation();
  125. } else {
  126. $(e.target).parent().trigger('click');
  127. }
  128. }).delegate('.kvov', 'mouseover', function (e) {
  129. $(this).addClass('x-hover');
  130. return false;
  131. }).delegate('.kvov', 'mouseout', function (e) {
  132. $(this).removeClass('x-hover');
  133. });
  134. JsonFormatEntrance.clear();
  135. JsonFormatEntrance.format(newSource);
  136. // 如果是JSONP格式的,需要把方法名也显示出来
  137. if (funcName != null) {
  138. $('#jfCallbackName_start').html(funcName + '(');
  139. $('#jfCallbackName_end').html(')');
  140. }
  141. }
  142. };
  143. var _init = function () {
  144. $(function () {
  145. if (!/^filesystem\:/.test(location.href)) {
  146. _format();
  147. }
  148. });
  149. };
  150. return {
  151. init: _init
  152. };
  153. })();
  154. baidu.csJsonFormat.init();