content-script.js 6.9 KB

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