请不要污染我的剪贴板

阻止网站未经许可操作剪贴板,保护用户剪贴板数据。

目前为 2024-11-28 提交的版本。查看 最新版本

// ==UserScript==
// @name         请不要污染我的剪贴板
// @namespace    Violentmonkey Scripts
// @version      0.3
// @description  阻止网站未经许可操作剪贴板,保护用户剪贴板数据。
// @license      MIT
// @match        *://*/*
// @grant        none
// ==/UserScript==
/* jshint esversion: 8 */

(function() {
    'use strict';

    // 覆盖 navigator.clipboard.writeText 方法
    const originalWriteText = navigator.clipboard.writeText;
    navigator.clipboard.writeText = async function(text) {
        const allowWrite = confirm('此网站试图写入内容到剪贴板,是否允许?');
        if (allowWrite) {
            return originalWriteText.call(navigator.clipboard, text);
        } else {
            alert('已拒绝写入剪贴板!');
            return Promise.reject('用户拒绝写入剪贴板');
        }
    };

    // 覆盖 document.execCommand 方法以拦截旧式的复制行为
    const originalExecCommand = document.execCommand;
    document.execCommand = function(command, ...args) {
        if (command.toLowerCase() === 'copy' || command.toLowerCase() === 'cut') {
            const allowExec = confirm(`此网站试图执行 "${command}" 操作,是否允许?`);
            if (!allowExec) {
                alert(`已拒绝 "${command}" 操作!`);
                return false;
            }
        }
        return originalExecCommand.apply(this, [command, ...args]);
    };

    // 拦截剪贴板事件并阻止未经授权的写入
    document.addEventListener('beforecopy', (e) => {
        const allowCopy = confirm('此网站试图复制内容到剪贴板,是否允许?');
        if (!allowCopy) {
            e.preventDefault();
            e.stopImmediatePropagation();
            alert('已阻止复制操作!');
        }
    });

    document.addEventListener('beforecut', (e) => {
        const allowCut = confirm('此网站试图剪切内容到剪贴板,是否允许?');
        if (!allowCut) {
            e.preventDefault();
            e.stopImmediatePropagation();
            alert('已阻止剪切操作!');
        }
    });

    // 添加对剪贴板 API 的全方位监控
    Object.defineProperty(navigator, 'clipboard', {
        configurable: false,
        enumerable: true,
        get: function() {
            alert('尝试访问 clipboard API,可能涉及剪贴板操作。');
            return originalWriteText;
        }
    });
})();