contentscript-jsonformat.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. /**
  28. * 从页面提取JSON文本
  29. * @return {*}
  30. * @private
  31. */
  32. var _getJsonText = function(){
  33. var source = $.trim($('body>pre:eq(0)').html());
  34. if (!source) {
  35. source = $.trim($('body').html())
  36. }
  37. if (!source) {
  38. return;
  39. }
  40. // 如果body的内容还包含HTML标签,肯定不是合法的json了
  41. // 如果是合法的json,也只可能有一个text节点
  42. var nodes = document.body.childNodes;
  43. var json_text_detected = false;
  44. for (var i = 0, len = nodes.length; i < len; i++) {
  45. if (nodes[i].nodeType == Node.TEXT_NODE) {
  46. if (!json_text_detected) {
  47. source = nodes[i].textContent;
  48. json_text_detected = true;
  49. } else {
  50. return;
  51. }
  52. } else if (nodes[i].nodeType == Node.ELEMENT_NODE) {
  53. var tagName = nodes[i].tagName.toLowerCase();
  54. var html = $.trim($(nodes[i]).html());
  55. // 如果是pre标签,则看内容是不是和source一样,一样则continue
  56. if(tagName === 'pre' && html === source) {
  57. continue;
  58. }
  59. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  60. else if (tagName === 'embed' && nodes[i].offsetWidth === 0) {
  61. continue;
  62. } else {
  63. return;
  64. }
  65. } else {
  66. return;
  67. }
  68. }
  69. return source;
  70. };
  71. /**
  72. * 执行format操作
  73. * @private
  74. */
  75. var _format = function () {
  76. var source = _getJsonText();
  77. if(!source) {
  78. return;
  79. }
  80. // JSONP形式下的callback name
  81. var funcName = null;
  82. // json对象
  83. var jsonObj = null;
  84. // 下面校验给定字符串是否为一个合法的json
  85. try {
  86. jsonObj = new Function("return " + source)();
  87. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  88. if (typeof jsonObj == "string") {
  89. // 再来一次
  90. jsonObj = new Function("return " + jsonObj)();
  91. }
  92. } catch (ex) {
  93. // 再看看是不是jsonp的格式
  94. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  95. var matches = reg.exec(source);
  96. if (matches == null) {
  97. return;
  98. }
  99. funcName = matches[1];
  100. source = matches[2];
  101. try {
  102. jsonObj = new Function("return " + source)();
  103. } catch (e) {
  104. return;
  105. }
  106. }
  107. // 是json格式,可以进行JSON自动格式化
  108. if (typeof jsonObj == "object") {
  109. try {
  110. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  111. source = JSON.stringify(jsonObj);
  112. } catch (ex) {
  113. // 通过JSON反解不出来的,一定有问题
  114. return;
  115. }
  116. $('body').html(_htmlFragment);
  117. _loadCss();
  118. JsonFormatEntrance.clear();
  119. JsonFormatEntrance.format(source);
  120. // 如果是JSONP格式的,需要把方法名也显示出来
  121. if (funcName != null) {
  122. $('#jfCallbackName_start').html(funcName + '(');
  123. $('#jfCallbackName_end').html(')');
  124. }
  125. // 允许禁用
  126. $('#makeAutoJsonFormatOff').click(function (e) {
  127. baidu.feOption.setOptions({
  128. "opt_item_autojson":'false'
  129. });
  130. alert("以后可以从FeHelper的选项页面中重新开启");
  131. window.location.reload(true);
  132. });
  133. }
  134. };
  135. var _init = function () {
  136. $(function () {
  137. baidu.feOption.getOptions(["opt_item_autojson"], function (opts) {
  138. if (opts["opt_item_autojson"] != 'false') {
  139. _format();
  140. }
  141. });
  142. });
  143. };
  144. return {
  145. init:_init
  146. };
  147. })();
  148. baidu.csJsonFormat.init();