contentscript-jsonformat.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. // 下面校验给定字符串是否为一个合法的json
  79. try {
  80. // 再看看是不是jsonp的格式
  81. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  82. var matches = reg.exec(source);
  83. if (matches != null) {
  84. funcName = matches[1];
  85. var newSource = matches[2];
  86. jsonObj = new Function("return " + newSource)();
  87. }
  88. } catch (ex) {
  89. return;
  90. }
  91. try {
  92. if (jsonObj == null || typeof jsonObj != 'object') {
  93. jsonObj = new Function("return " + source)();
  94. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  95. if (typeof jsonObj == "string") {
  96. // 再来一次
  97. jsonObj = new Function("return " + jsonObj)();
  98. }
  99. }
  100. } catch (e) {
  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. $('body').html(_htmlFragment);
  113. _loadCss();
  114. // 点击区块高亮
  115. $('#jfContent').delegate('.kvov', 'click', function (e) {
  116. $('#jfContent .kvov').removeClass('x-outline');
  117. $(this).removeClass('x-hover').addClass('x-outline');
  118. if (!$(e.target).is('.kvov .e')) {
  119. e.stopPropagation();
  120. } else {
  121. $(e.target).parent().trigger('click');
  122. }
  123. }).delegate('.kvov', 'mouseover', function (e) {
  124. $(this).addClass('x-hover');
  125. return false;
  126. }).delegate('.kvov', 'mouseout', function (e) {
  127. $(this).removeClass('x-hover');
  128. });
  129. JsonFormatEntrance.clear();
  130. JsonFormatEntrance.format(source);
  131. // 如果是JSONP格式的,需要把方法名也显示出来
  132. if (funcName != null) {
  133. $('#jfCallbackName_start').html(funcName + '(');
  134. $('#jfCallbackName_end').html(')');
  135. }
  136. }
  137. };
  138. var _init = function () {
  139. $(function () {
  140. if (!/^filesystem\:/.test(location.href)) {
  141. _format();
  142. }
  143. });
  144. };
  145. return {
  146. init: _init
  147. };
  148. })();
  149. baidu.csJsonFormat.init();