contentscript-jsonformat.js 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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="jfContent"></div>',
  18. '<pre id="jfContent_pre"></pre>',
  19. '</div></div>'
  20. ].join('');
  21. var _loadCss = function(){
  22. var fcpCss = chrome.extension.getURL('static/css/fe-jsonformat.css');
  23. jQuery('<link id="_fehelper_fcp_css_" href="' + fcpCss + '" rel="stylesheet" type="text/css" />').appendTo('head');
  24. };
  25. var _format = function(){
  26. var source ;
  27. if($('body').children().length == 1) {
  28. source = $.trim($('body>pre').html()) ;
  29. }
  30. if(!source) {
  31. source = $.trim($('body').html())
  32. }
  33. if(!source) {
  34. return;
  35. }
  36. var jsonObj = null;
  37. try{
  38. jsonObj = new Function("return " + source)();
  39. // 还要防止下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  40. if(typeof jsonObj == "string") {
  41. // 再来一次
  42. jsonObj = new Function("return " + jsonObj)();
  43. }
  44. if(typeof jsonObj == "object") {
  45. $('body').html(_htmlFragment);
  46. _loadCss();
  47. JsonFormatEntrance.clear();
  48. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  49. source = JSON.stringify(jsonObj);
  50. JsonFormatEntrance.format(source);
  51. // 允许禁用
  52. $('#makeAutoJsonFormatOff').click(function(e){
  53. baidu.feOption.setOptions({
  54. "opt_item_autojson" : 'false'
  55. });
  56. alert("以后可以从FeHelper的选项页面中重新开启");
  57. window.location.reload(true);
  58. });
  59. }
  60. }catch(ex){
  61. return;
  62. }
  63. };
  64. var _init = function(){
  65. $(function(){
  66. baidu.feOption.getOptions(["opt_item_autojson"],function(opts){
  67. if(opts["opt_item_autojson"] != 'false') {
  68. _format();
  69. }
  70. });
  71. });
  72. };
  73. return {
  74. init : _init
  75. };
  76. })();
  77. baidu.csJsonFormat.init();