contentscript-jsonformat.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. * @returns {string}
  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) && ['script', 'link'].indexOf(tagName) == -1) {
  51. // 如果用户安装迅雷或者其他的插件,也回破坏页面结构,需要兼容一下
  52. continue;
  53. } else {
  54. return false;
  55. }
  56. } else {
  57. return false;
  58. }
  59. }
  60. return $.trim(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. * chrome 下复制到剪贴板
  84. * @param text
  85. */
  86. var _copyToClipboard = function (text) {
  87. var input = document.createElement('textarea');
  88. input.style.position = 'fixed';
  89. input.style.opacity = 0;
  90. input.value = text;
  91. document.body.appendChild(input);
  92. input.select();
  93. document.execCommand('Copy');
  94. document.body.removeChild(input);
  95. alert('Json片段复制成功,随处粘贴可用!')
  96. };
  97. /**
  98. * 给某个节点增加操作项
  99. * @param el
  100. * @private
  101. */
  102. var _addOptForItem = function (el) {
  103. // 下载json片段
  104. var fnDownload = function (ec) {
  105. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  106. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  107. txt = '{' + txt + '}';
  108. }
  109. try {
  110. txt = JSON.stringify(JSON.parse(txt), null, 4);
  111. } catch (err) {
  112. }
  113. // 下载片段
  114. var dt = (new Date()).format('yyyyMMddHHmmss');
  115. var blob = new Blob([txt], {type: 'application/octet-stream'});
  116. $(this).attr('download', 'FeHelper-' + dt + '.json').attr('href', URL.createObjectURL(blob));
  117. };
  118. // 复制json片段
  119. var fnCopy = function (ec) {
  120. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  121. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  122. txt = '{' + txt + '}';
  123. }
  124. try {
  125. txt = JSON.stringify(JSON.parse(txt), null, 4);
  126. } catch (err) {
  127. }
  128. _copyToClipboard(txt);
  129. };
  130. // 删除json片段
  131. var fnDel = function (ed) {
  132. if (el.parent().is('#formattedJson')) {
  133. alert('如果连最外层的Json也删掉的话,就没啥意义了哦!');
  134. return false;
  135. }
  136. alert('节点已删除成功!');
  137. el.remove();
  138. boxOpt.css('top', -1000).hide();
  139. };
  140. var boxOpt = $('#boxOpt');
  141. if (!boxOpt.length) {
  142. boxOpt = $('<div id="boxOpt"><a class="opt-download" target="_blank">下载</a>|<a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  143. }
  144. boxOpt.find('a.opt-download').unbind('click').bind('click', fnDownload);
  145. boxOpt.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  146. boxOpt.find('a.opt-del').unbind('click').bind('click', fnDel);
  147. boxOpt.css({
  148. left: el.offset().left + el.width() - 90,
  149. top: el.offset().top
  150. }).show();
  151. };
  152. /**
  153. * 事件绑定
  154. * @private
  155. */
  156. var _bindEvent = function () {
  157. // 点击区块高亮
  158. $('#jfContent').delegate('.kvov', 'click', function (e) {
  159. if($(this).hasClass('x-outline')) {
  160. $('#boxOpt').remove();
  161. $(this).removeClass('x-outline');
  162. return false;
  163. }
  164. $('#jfContent .kvov').removeClass('x-outline');
  165. var el = $(this).removeClass('x-hover').addClass('x-outline');
  166. // 增加复制、删除功能
  167. _addOptForItem(el);
  168. if (!$(e.target).is('.kvov .e')) {
  169. e.stopPropagation();
  170. } else {
  171. $(e.target).parent().trigger('click');
  172. }
  173. }).delegate('.kvov', 'mouseover', function (e) {
  174. $(this).addClass('x-hover');
  175. return false;
  176. }).delegate('.kvov', 'mouseout', function (e) {
  177. $(this).removeClass('x-hover');
  178. });
  179. };
  180. /**
  181. * 执行format操作
  182. * @private
  183. */
  184. var _format = function () {
  185. var source = _getJsonText();
  186. if (!source) {
  187. return;
  188. }
  189. // JSONP形式下的callback name
  190. var funcName = null;
  191. // json对象
  192. var jsonObj = null;
  193. var newSource = source;
  194. var fnTry = null;
  195. var fnCatch = null;
  196. // 下面校验给定字符串是否为一个合法的json
  197. try {
  198. // 再看看是不是jsonp的格式
  199. var reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/gm;
  200. var reTry = /^(try\s*\{\s*)?/g;
  201. var reCatch = /(\}\s*catch\s*\(\s*\S+\s*\)\s*\{([\s\S])*\})?$/g;
  202. // 检测是否有try-catch包裹
  203. var sourceReplaced = source.replace(reTry, function () {
  204. fnTry = fnTry ? fnTry : arguments[1];
  205. return '';
  206. }).replace(reCatch, function () {
  207. fnCatch = fnCatch ? fnCatch : arguments[1];
  208. return '';
  209. }).trim();
  210. var matches = reg.exec(sourceReplaced);
  211. if (matches != null && (fnTry && fnCatch || !fnTry && !fnCatch)) {
  212. funcName = matches[1];
  213. newSource = matches[2];
  214. jsonObj = new Function("return " + newSource)();
  215. } else {
  216. reg = /^([\{\[])/;
  217. if (!reg.test(source)) {
  218. return;
  219. }
  220. }
  221. // 强化验证
  222. if (jsonObj == null || typeof jsonObj != 'object') {
  223. jsonObj = new Function("return " + source)();
  224. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  225. if (typeof jsonObj == "string") {
  226. // 再来一次
  227. jsonObj = new Function("return " + jsonObj)();
  228. }
  229. }
  230. } catch (ex) {
  231. return;
  232. }
  233. // 是json格式,可以进行JSON自动格式化
  234. if (jsonObj != null && typeof jsonObj == "object") {
  235. try {
  236. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  237. var jsonStr = JSON.stringify(jsonObj);
  238. // 如果newSource的长度比原source长度短很多的话,猜测应该是格式化错了,需要撤销操作
  239. // 这里一定要unicode decode一下,要不然会出现误判
  240. var len1 = jsonStr.replace(/'|"|\s/g, '').length;
  241. var len2 = (_uniDecode(newSource)).replace(/'|"|\s/g, '').length;
  242. // 误差不允许超过20%
  243. if (Math.abs(len1 - len2) / ((len1 + len2) / 2) > 0.2) {
  244. return;
  245. }
  246. newSource = jsonStr;
  247. } catch (ex) {
  248. // 通过JSON反解不出来的,一定有问题
  249. return;
  250. }
  251. $('body').html(_htmlFragment);
  252. _loadCss();
  253. _bindEvent();
  254. JsonFormatEntrance.clear();
  255. JsonFormatEntrance.format(newSource);
  256. // 如果是JSONP格式的,需要把方法名也显示出来
  257. if (funcName != null) {
  258. if (fnTry && fnCatch) {
  259. $('#jfCallbackName_start').html('<pre style="padding:0">' + fnTry + '</pre>' + funcName + '(');
  260. $('#jfCallbackName_end').html(')<br><pre style="padding:0">' + fnCatch + '</pre>');
  261. } else {
  262. $('#jfCallbackName_start').html(funcName + '(');
  263. $('#jfCallbackName_end').html(')');
  264. }
  265. }
  266. }
  267. };
  268. var _init = function () {
  269. $(function () {
  270. if (baidu.feOption.pageJsonMustFormat) {
  271. _format();
  272. } else {
  273. chrome.extension.sendMessage({
  274. type: MSG_TYPE.GET_OPTIONS,
  275. items: ['JSON_PAGE_FORMAT']
  276. }, function (opts) {
  277. if (!opts || opts.JSON_PAGE_FORMAT != 'false') {
  278. _format();
  279. }
  280. });
  281. }
  282. });
  283. };
  284. return {
  285. init: _init
  286. };
  287. })();
  288. baidu.csJsonFormat.init();