codebeautify.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 = '<pre class="brush: css;toolbar:true;">' + css + '</pre>';
  29. $('#jfContent').html(css);
  30. } else if (codeType == 'HTML') {
  31. var html = html_beautify($('#codeSource').val());
  32. html = '<pre class="brush: html;toolbar:false;">' + html + '</pre>';
  33. $('#jfContent').html(html);
  34. }
  35. // 代码高亮
  36. SyntaxHighlighter.defaults['toolbar'] = false;
  37. SyntaxHighlighter.highlight();
  38. };
  39. var bindEvent = function () {
  40. $('input[name="codeType"]').click(function (e) {
  41. codeType = this.value;
  42. $('#codeTitle').html(this.value);
  43. });
  44. $('#btnFormat').click(function (e) {
  45. _format();
  46. });
  47. };
  48. var init = function () {
  49. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  50. chrome.runtime.onMessage.addListener(function (request, sender, callback) {
  51. console.log(request);
  52. if (request.type == MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event == 'codebeautify') {
  53. if (request.content) {
  54. document.getElementById('codeSource').value = (request.content);
  55. _format();
  56. }
  57. }
  58. });
  59. $(function () {
  60. //输入框聚焦
  61. jQuery("#codeSource").focus();
  62. bindEvent();
  63. })
  64. };
  65. return {
  66. init: init
  67. };
  68. })();
  69. CodeBeautify.init();