选择自动复制-解除复制限制

Auoto Copy Select Text.

  1. // ==UserScript==
  2. // @name 选择自动复制-解除复制限制
  3. // @namespace http://tampermonkey.net/
  4. // @version 2024-12-26
  5. // @description Auoto Copy Select Text.
  6. // @author M&W
  7. // @match *://*/*
  8. // @include *
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=51cto.com
  10. // @grant none
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16. // 复制文本到剪贴板的函数
  17. function copyToClipboard(text, e) {
  18. var textarea = document.createElement('textarea');
  19. textarea.value = text;
  20. textarea.style.position = 'absolute';
  21. textarea.style.left = '-9999px';
  22. textarea.style.top = '-9999px';
  23. document.body.appendChild(textarea);
  24. textarea.select();
  25. try {
  26. var successful = document.execCommand('copy');
  27. console.log(successful ? 'Text copied to clipboard' : 'Failed to copy text');
  28. } catch (err) {
  29. console.error('Failed to copy text: ', err);
  30. }
  31. document.body.removeChild(textarea);
  32. showCopyMessage(e)
  33. }
  34. var copyMessage = undefined;
  35. function showCopyMessage(e) {
  36. // 创建提示信息
  37. if(copyMessage == undefined){
  38. copyMessage = document.createElement('div');
  39. }
  40. copyMessage.textContent = '已复制';
  41. copyMessage.style.position = 'absolute';
  42. copyMessage.style.backgroundColor = '#fff';
  43. copyMessage.style.color = 'black';
  44. copyMessage.style.borderRadius = '4px';
  45. copyMessage.style.padding = '5px 10px';
  46. copyMessage.style.fontSize = '14px';
  47. copyMessage.style.fontWeight = 'bold';
  48. copyMessage.style.zIndex = '10000';
  49. document.body.appendChild(copyMessage);
  50.  
  51. // 定位提示信息到按钮下方
  52. copyMessage.style.left = `${e.pageX + 15}px`;
  53. copyMessage.style.top = `${e.pageY + 15}px`;
  54.  
  55. // 2秒后移除提示信息
  56. setTimeout(function () {
  57. copyMessage.remove();
  58. }, 1000);
  59. }
  60. // 鼠标释放事件,检查是否有文本被选中
  61. document.addEventListener('mouseup', function (e) {
  62. var selectedText = window.getSelection().toString().trim();
  63. if (selectedText.length > 0) {
  64. copyToClipboard(selectedText, e);
  65. }
  66. });
  67. })();