codebeautify.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * 代码格式化
  3. * @author 赵先烈
  4. */
  5. var CodeBeautify = (function () {
  6. var opts = {
  7. brace_style: "collapse",
  8. break_chained_methods: false,
  9. indent_char: " ",
  10. indent_scripts: "keep",
  11. indent_size: "4",
  12. keep_array_indentation: true,
  13. preserve_newlines: true,
  14. space_after_anon_function: true,
  15. space_before_conditional: true,
  16. unescape_strings: false,
  17. wrap_line_length: "120"
  18. };
  19. var codeType = 'Javascript';
  20. var _format = function () {
  21. if (codeType == 'Javascript') {
  22. var js = js_beautify($('#codeSource').val(), opts);
  23. js = js.replace(/>/g, '&gt;').replace(/</g, '&lt;');
  24. js = '<pre class="brush: js;toolbar:false;">' + js + '</pre>';
  25. $('#jfContent').html(js);
  26. } else if (codeType == 'CSS') {
  27. var css = css_beautify($('#codeSource').val());
  28. css = css.replace(/>/g, '&gt;').replace(/</g, '&lt;');
  29. css = '<pre class="brush: css;toolbar:true;">' + css + '</pre>';
  30. $('#jfContent').html(css);
  31. } else if (codeType == 'HTML') {
  32. var html = html_beautify($('#codeSource').val());
  33. html = html.replace(/>/g, '&gt;').replace(/</g, '&lt;');
  34. html = '<pre class="brush: html;toolbar:false;">' + html + '</pre>';
  35. $('#jfContent').html(html);
  36. } else if (codeType == 'XML') {
  37. var xml = vkbeautify.xml($('#codeSource').val());
  38. xml = xml.replace(/>/g, '&gt;').replace(/</g, '&lt;');
  39. xml = '<pre class="brush: html;toolbar:false;">' + xml + '</pre>';
  40. $('#jfContent').html(xml);
  41. } else if (codeType == 'SQL') {
  42. var sql = vkbeautify.sql($('#codeSource').val(),4);
  43. sql = sql.replace(/>/g, '&gt;').replace(/</g, '&lt;');
  44. sql = '<pre class="brush: sql;toolbar:false;">' + sql + '</pre>';
  45. $('#jfContent').html(sql);
  46. }
  47. // 代码高亮
  48. SyntaxHighlighter.defaults['toolbar'] = false;
  49. SyntaxHighlighter.highlight();
  50. };
  51. var bindEvent = function () {
  52. $('input[name="codeType"]').click(function (e) {
  53. codeType = this.value;
  54. $('#codeTitle').html(this.value);
  55. });
  56. $('#btnFormat').click(function (e) {
  57. _format();
  58. });
  59. };
  60. var init = function () {
  61. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  62. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  63. if (request.type == MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event == 'codebeautify') {
  64. if (request.content) {
  65. document.getElementById('codeSource').value = (request.content);
  66. _format();
  67. }
  68. }
  69. });
  70. $(function () {
  71. //输入框聚焦
  72. jQuery("#codeSource").focus();
  73. bindEvent();
  74. })
  75. };
  76. return {
  77. init: init
  78. };
  79. })();
  80. CodeBeautify.init();