Greasy Fork

Greasy Fork is available in English.

防止未经授权的自动复制

在非选词复制时显示小红点提示用户以防止未经授权的自动复制。

当前为 2023-10-02 提交的版本,查看 最新版本

// ==UserScript==
// @name 防止未经授权的自动复制
// @version 9
// @author ChatGPT
// @description 在非选词复制时显示小红点提示用户以防止未经授权的自动复制。
// @grant GM_setClipboard
// @run-at document-start
// @match *://*/*
// @namespace http://greasyfork.icu/users/452911
// ==/UserScript==

(function() {
  'use strict';

  let hasCopied = false;
  let timeoutId = null;
  
  const handleCopy = function(event) {
    event.preventDefault();
    const selection = window.getSelection().toString();
    if (!hasCopied) {
      hasCopied = true;
      const dot = document.createElement('div');
      dot.style.width = '20px';
      dot.style.height = '20px';
      dot.style.zIndex = '9999';
      dot.style.background = 'red';
      dot.style.borderRadius = '50%';
      dot.style.position = 'fixed';
      dot.style.top = '50%';
      dot.style.right = '10px';
      dot.style.transform = 'translateY(-50%)';
      dot.style.cursor = 'pointer';
      dot.addEventListener('click', function() {
        const shouldCopy = confirm('是否复制?\n' + selection);
        if (shouldCopy) {
          GM_setClipboard(selection);
        }
        document.body.removeChild(dot);
        hasCopied = false;
      });
      document.body.appendChild(dot);
      
      timeoutId = setTimeout(function() {
        document.body.removeChild(dot);
        hasCopied = false;
        timeoutId = null;
      }, 2000); // 设置延时时间,单位为毫秒
    }
  };
  
  const handleSelectionChange = function() {
    const selection = window.getSelection().toString();
    if (selection.length === 0) {
      document.addEventListener('copy', handleCopy);
    } else {
      document.removeEventListener('copy', handleCopy);
    }
  };

  document.addEventListener('copy', handleCopy);
  document.addEventListener('selectionchange', handleSelectionChange);

  // 在页面卸载前清除延时器
  window.addEventListener('beforeunload', function() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
  });
})();