content-script.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. window.codebeautifyContentScript = (() => {
  2. let __importScript = (filename) => {
  3. let url = filename;
  4. if (location.protocol === 'chrome-extension:' || chrome.runtime && chrome.runtime.getURL) {
  5. url = chrome.runtime.getURL('code-beautify/' + filename);
  6. }
  7. fetch(url).then(resp => resp.text()).then(jsText => {
  8. if(window.evalCore && window.evalCore.getEvalInstance){
  9. return window.evalCore.getEvalInstance(window)(jsText);
  10. }
  11. let el = document.createElement('script');
  12. el.textContent = jsText;
  13. document.head.appendChild(el);
  14. });
  15. };
  16. __importScript('beautify.js');
  17. __importScript('beautify-css.js');
  18. let highlightWebWorker = () => {
  19. // TODO ...
  20. // __importScript('../static/vendor/highlight/highlight.js');
  21. self.onmessage = (event) => {
  22. // const result = self.hljs.highlightAuto(event.data);
  23. // postMessage(result.value);
  24. postMessage(event.data);
  25. };
  26. };
  27. let formattedCodes = '';
  28. // **************************************************************
  29. /**
  30. * 代码美化
  31. */
  32. let format = (fileType, source, callback) => {
  33. let beauty = txtResult => {
  34. let code = document.getElementsByTagName('pre')[0];
  35. formattedCodes = txtResult;
  36. code.textContent = txtResult;
  37. code.classList.add('language-' + fileType.toLowerCase());
  38. // 用webwork的方式来进行格式化,效率更高
  39. let worker = new Worker(URL.createObjectURL(new Blob(["(" + highlightWebWorker.toString() + ")()"], {type: 'text/javascript'})));
  40. worker.onmessage = (event) => {
  41. code.innerHTML = "<ol><li><span>" + event.data.replace(/\n/gm, '</span></li><li><span>') + '</span></li></ol>';
  42. callback && callback();
  43. };
  44. worker.postMessage(txtResult);
  45. };
  46. switch (fileType) {
  47. case 'javascript':
  48. let opts = {
  49. brace_style: "collapse",
  50. break_chained_methods: false,
  51. indent_char: " ",
  52. indent_scripts: "keep",
  53. indent_size: "4",
  54. keep_array_indentation: true,
  55. preserve_newlines: true,
  56. space_after_anon_function: true,
  57. space_before_conditional: true,
  58. unescape_strings: false,
  59. wrap_line_length: "120"
  60. };
  61. beauty(js_beautify(source, opts));
  62. break;
  63. case 'css':
  64. css_beautify(source, {}, resp => beauty(resp));
  65. break;
  66. }
  67. };
  68. /**
  69. * 检测
  70. * @returns {boolean}
  71. */
  72. window._codebutifydetect_ = (fileType) => {
  73. if (!document.getElementsByTagName('pre')[0]) {
  74. return;
  75. }
  76. let source = document.getElementsByTagName('pre')[0].textContent;
  77. $(document.body).addClass('show-tipsbar');
  78. let tipsBar = $('<div id="fehelper_tips">' +
  79. '<span class="desc">FeHelper检测到这可能是<i>' + fileType + '</i>代码,<span class="ask">是否进行美化处理?</span></span>' +
  80. '<a class="encoding">有乱码?点击修正!</a>' +
  81. '<button class="yes">代码美化</button>' +
  82. '<button class="no">放弃!</button>' +
  83. '<button class="copy hide">复制美化过的代码</button>' +
  84. '<button class="close"><span></span></button>' +
  85. '<a class="forbid">彻底关闭这个功能!&gt;&gt;</a>' +
  86. '</div>').prependTo('body');
  87. tipsBar.find('button.yes').click((evt) => {
  88. tipsBar.find('button.yes,button.no').hide();
  89. let elAsk = tipsBar.find('span.ask').text('正在努力美化,请稍候...');
  90. format(fileType, source, () => {
  91. elAsk.text('已为您美化完毕!');
  92. $(document.body).removeClass('show-tipsbar').addClass('show-beautified');
  93. });
  94. });
  95. tipsBar.find('a.forbid').click((evt) => {
  96. evt.preventDefault();
  97. if (confirm('一旦彻底关闭,不可恢复,请确认?')) {
  98. chrome.runtime.sendMessage({
  99. type: 'fh-dynamic-any-thing',
  100. thing: 'close-beautify'
  101. }, () => {
  102. alert('已关闭,如果要恢复,请在FeHelper「设置页」重新安装「代码美化工具」!');
  103. });
  104. }
  105. });
  106. tipsBar.find('button.no,button.close').click((evt) => {
  107. $(document.body).removeClass('show-tipsbar').removeClass('show-beautified');
  108. tipsBar.remove();
  109. });
  110. tipsBar.find('button.copy').click((evt) => {
  111. _copyToClipboard(formattedCodes);
  112. });
  113. tipsBar.find('a.encoding').click((evt) => {
  114. evt.preventDefault();
  115. fetch(location.href).then(res => res.text()).then(text => {
  116. source = text;
  117. if ($(document.body).hasClass('show-beautified')) {
  118. tipsBar.find('button.yes').trigger('click');
  119. } else {
  120. $('#fehelper_tips+pre').text(text);
  121. }
  122. });
  123. });
  124. };
  125. /**
  126. * chrome 下复制到剪贴板
  127. * @param text
  128. */
  129. let _copyToClipboard = function (text) {
  130. let input = document.createElement('textarea');
  131. input.style.position = 'fixed';
  132. input.style.opacity = 0;
  133. input.value = text;
  134. document.body.appendChild(input);
  135. input.select();
  136. document.execCommand('Copy');
  137. document.body.removeChild(input);
  138. alert('代码复制成功,随处粘贴可用!')
  139. };
  140. return function () {
  141. let ext = location.pathname.substring(location.pathname.lastIndexOf(".") + 1).toLowerCase();
  142. let fileType = ({'js': 'javascript', 'css': 'css'})[ext];
  143. let contentType = document.contentType.toLowerCase();
  144. if (!fileType) {
  145. if (/\/javascript$/.test(contentType)) {
  146. fileType = 'javascript';
  147. } else if (/\/css$/.test(contentType)) {
  148. fileType = 'css';
  149. }
  150. } else if (contentType === 'text/html') {
  151. fileType = undefined;
  152. }
  153. chrome.runtime.sendMessage({
  154. type: 'fh-dynamic-any-thing',
  155. thing: 'code-beautify',
  156. params: { fileType, tabId: window.__FH_TAB_ID__ || null }
  157. });
  158. };
  159. })();