content-script.js 7.0 KB

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