contentscript-jsonformat.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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></div>',
  10. '<div id="formattingMsg">',
  11. '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">',
  12. '<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>',
  13. '</svg>加载中...',
  14. '</div>',
  15. '<div id="jfContent"></div>',
  16. '<pre id="jfContent_pre"></pre>',
  17. '</div></div>'
  18. ].join('');
  19. var _loadCss = function(){
  20. var fcpCss = chrome.extension.getURL('static/css/fe-jsonformat.css');
  21. jQuery('<link id="_fehelper_fcp_css_" href="' + fcpCss + '" rel="stylesheet" type="text/css" />').appendTo('head');
  22. };
  23. var _init = function(){
  24. $(function(){
  25. var source = $.trim($('body>pre').html()) || $.trim($('body').html());
  26. var isJson = true;
  27. var jsonObj = null;
  28. try{
  29. jsonObj = JSON.parse(source);
  30. }catch(ex){
  31. isJson = false;
  32. try{
  33. jsonObj = new Function("return " + source)();
  34. isJson = true;
  35. }catch(ex){
  36. }
  37. }
  38. if(isJson && jsonObj) {
  39. $('body').html(_htmlFragment);
  40. _loadCss();
  41. JsonFormatEntrance.clear();
  42. JsonFormatEntrance.format(source);
  43. }
  44. });
  45. };
  46. return {
  47. init : _init
  48. };
  49. })();
  50. baidu.csJsonFormat.init();