contentscript-jsonformat.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. '&nbsp;&nbsp;或者&nbsp;&nbsp;<a href="#" id="makeAutoJsonFormatOff">禁用此功能</a>',
  11. '</div>',
  12. '<div id="formattingMsg">',
  13. '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">',
  14. '<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>',
  15. '</svg>加载中...',
  16. '</div>',
  17. '<div id="jfCallbackName_start" class="callback-name"></div>',
  18. '<div id="jfContent"></div>',
  19. '<pre id="jfContent_pre"></pre>',
  20. '<div id="jfCallbackName_end" class="callback-name"></div>',
  21. '</div></div>'
  22. ].join('');
  23. var _loadCss = function () {
  24. var fcpCss = chrome.extension.getURL('static/css/fe-jsonformat.css');
  25. jQuery('<link id="_fehelper_fcp_css_" href="' + fcpCss + '" rel="stylesheet" type="text/css" />').appendTo('head');
  26. };
  27. var _unEscapeHTML = function(txt) {
  28. return txt.replace(/&amp;/g,'&').replace(/&gt;/g,'>')
  29. .replace(/&lt;/g,'<').replace(/&quot;/g,'"')
  30. .replace(/&#39;/g,"'");
  31. };
  32. /**
  33. * 从页面提取JSON文本
  34. * @return {*}
  35. * @private
  36. */
  37. var _getJsonText = function(){
  38. var source = $.trim($('body>pre:eq(0)').html());
  39. if (!source) {
  40. source = $.trim($('body').html())
  41. }
  42. if (!source) {
  43. return;
  44. }
  45. // jQuery的html方法是把内容编码后输出的,所以需要反解回去
  46. source = _unEscapeHTML(source);
  47. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  48. // 如果是合法的json,也只可能有一个text节点
  49. var nodes = document.body.childNodes;
  50. var json_text_detected = false;
  51. for (var i = 0, len = nodes.length; i < len; i++) {
  52. if (nodes[i].nodeType == Node.TEXT_NODE) {
  53. if (!json_text_detected) {
  54. source = nodes[i].textContent;
  55. json_text_detected = true;
  56. } else {
  57. return;
  58. }
  59. } else if (nodes[i].nodeType == Node.ELEMENT_NODE) {
  60. var tagName = nodes[i].tagName.toLowerCase();
  61. var html = $.trim(_unEscapeHTML($(nodes[i]).html()));
  62. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  63. if(tagName === 'pre' && html === source) {
  64. continue;
  65. }
  66. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  67. else if (tagName === 'embed' && nodes[i].offsetWidth === 0) {
  68. continue;
  69. } else {
  70. return;
  71. }
  72. } else {
  73. return;
  74. }
  75. }
  76. return source;
  77. };
  78. /**
  79. * 执行format操作
  80. * @private
  81. */
  82. var _format = function () {
  83. var source = _getJsonText();
  84. if(!source) {
  85. return;
  86. }
  87. // JSONP形式下的callback name
  88. var funcName = null;
  89. // json对象
  90. var jsonObj = null;
  91. // 下面校验给定字符串是否为一个合法的json
  92. try {
  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. } catch (ex) {
  100. // 再看看是不是jsonp的格式
  101. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  102. var matches = reg.exec(source);
  103. if (matches == null) {
  104. return;
  105. }
  106. funcName = matches[1];
  107. source = matches[2];
  108. try {
  109. jsonObj = new Function("return " + source)();
  110. } catch (e) {
  111. return;
  112. }
  113. }
  114. // 是json格式,可以进行JSON自动格式化
  115. if (typeof jsonObj == "object") {
  116. try {
  117. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  118. source = JSON.stringify(jsonObj);
  119. } catch (ex) {
  120. // 通过JSON反解不出来的,一定有问题
  121. return;
  122. }
  123. $('body').html(_htmlFragment);
  124. _loadCss();
  125. JsonFormatEntrance.clear();
  126. JsonFormatEntrance.format(source);
  127. // 如果是JSONP格式的,需要把方法名也显示出来
  128. if (funcName != null) {
  129. $('#jfCallbackName_start').html(funcName + '(');
  130. $('#jfCallbackName_end').html(')');
  131. }
  132. // 允许禁用
  133. $('#makeAutoJsonFormatOff').click(function (e) {
  134. baidu.feOption.setOptions({
  135. "opt_item_autojson":'false'
  136. });
  137. alert("以后可以从FeHelper的选项页面中重新开启");
  138. window.location.reload(true);
  139. });
  140. }
  141. };
  142. var _init = function () {
  143. $(function () {
  144. baidu.feOption.getOptions(["opt_item_autojson"], function (opts) {
  145. if (opts["opt_item_autojson"] != 'false') {
  146. _format();
  147. }
  148. });
  149. });
  150. };
  151. return {
  152. init:_init
  153. };
  154. })();
  155. baidu.csJsonFormat.init();