Copy it

Hold Alt click on text, Copy as plain text. Alt + Shift click on text, Copy as kebab-case.

当前为 2022-12-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Copy it
  3. // @name:zh-CN 便捷复制
  4. // @namespace https://github.com/xianghongai/Tampermonkey-UserScript
  5. // @version 1.0.2
  6. // @description Hold Alt click on text, Copy as plain text. Alt + Shift click on text, Copy as kebab-case.
  7. // @description:zh-CN 按住 Alt 键点击文本,复制为纯文本。Alt + Shift 复制为 kebab-case 风格字符。
  8. // @author Nicholas Hsiang
  9. // @icon https://xinlu.ink/favicon.ico
  10. // @match http*://*/*
  11. // @grant none
  12. // @license MIT
  13. // ==/UserScript==
  14.  
  15. (function () {
  16. 'use strict';
  17.  
  18. document.addEventListener('click', listener, false);
  19.  
  20. function listener(event) {
  21. if (event.altKey) {
  22. event.preventDefault();
  23. event.stopPropagation();
  24. const text = event.target.innerText;
  25. if (event.shiftKey) {
  26. copyTextToClipboard(toKebab(text));
  27. return false;
  28. }
  29. copyTextToClipboard(text);
  30. return false;
  31. }
  32. }
  33.  
  34. function wrapperMsg(input) {
  35. const prefix = `__Tampermonkey® (Hold Ctrl + Alt or Alt click on text, copy it)__: `;
  36. return `${prefix}${input}`;
  37. }
  38.  
  39. function toKebab(input) {
  40. if (typeof input === 'string') {
  41. return input
  42. .replace(/[\W\s]/gi, '-')
  43. .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
  44. .replace(/([A-Z])([A-Z])(?=[a-z])/g, '$1-$2')
  45. .toLowerCase();
  46. }
  47. }
  48.  
  49. function fallbackCopyTextToClipboard(text) {
  50. let textArea = document.createElement('textarea');
  51. textArea.value = text;
  52.  
  53. // Avoid scrolling to bottom
  54. textArea.style.top = '0';
  55. textArea.style.left = '0';
  56. textArea.style.position = 'fixed';
  57.  
  58. document.body.appendChild(textArea);
  59. textArea.focus();
  60. textArea.select();
  61.  
  62. try {
  63. var successful = document.execCommand('copy');
  64. var msg = successful ? 'successful' : 'unsuccessful';
  65. console.log(wrapperMsg('Copying text command was ' + msg));
  66. } catch (err) {
  67. console.error(wrapperMsg('Oops, unable to copy'), err);
  68. }
  69.  
  70. document.body.removeChild(textArea);
  71. }
  72.  
  73. function copyTextToClipboard(text) {
  74. if (!navigator.clipboard) {
  75. fallbackCopyTextToClipboard(text);
  76. return;
  77. }
  78. navigator.clipboard.writeText(text).then(
  79. function () {
  80. console.log(wrapperMsg('Copying to clipboard was successful!'));
  81. },
  82. function (err) {
  83. console.error(wrapperMsg('Could not copy text: '), err);
  84. }
  85. );
  86. }
  87. })();