Greasy Fork

Greasy Fork is available in English.

TX元宝上传增强

自动为粘贴的不支持文件类型添加.txt后缀并修正MIME类型。可能仍会提示不支持,但看到上传成功即可。拖入,选择方式尚未修改。

目前为 2025-02-22 提交的版本,查看 最新版本

// ==UserScript==
// @name         TX元宝上传增强
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  自动为粘贴的不支持文件类型添加.txt后缀并修正MIME类型。可能仍会提示不支持,但看到上传成功即可。拖入,选择方式尚未修改。
// @author       yooyi
// @match        *://yuanbao.tencent.com/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 需要添加.txt后缀的类型名
    const UNSUPPORTED_EXT = ['.dart', '.py', '.java', '.js', '.cpp', '.kt', '.swift', '.html', '.css', '.sql'
                            , '.php', '.c', '.vbs', '.xml', '.ini', '.md', '.yml', '.yaml'];

    document.addEventListener('paste', function(e) {
        const items = e.clipboardData.items;
        const files = [];
        let shouldModify = false;

        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.kind === 'file') {
                const file = item.getAsFile();
                const originalName = file.name;

                if (UNSUPPORTED_EXT.some(ext =>
                    originalName.toLowerCase().endsWith(ext)
                )) {
                    shouldModify = true;
                    // 关键修改:强制指定MIME类型为text/plain
                    const newFile = new File(
                        [file],
                        `${originalName}.txt`,
                        { type: 'text/plain' } // 强制覆盖为文本类型
                    );
                    files.push(newFile);
                } else {
                    files.push(file);
                }
            }
        }

        if (shouldModify) {
            e.preventDefault();
            const newData = new DataTransfer();
            files.forEach(f => newData.items.add(f));

            // 更可靠的焦点目标获取方式
            const target = document.activeElement.closest('input, [contenteditable]') || document.activeElement;

            // 使用更兼容的事件触发方式
            if (target instanceof HTMLInputElement) {
                target.files = newData.files;
            } else {
                const pasteEvent = new ClipboardEvent('paste', {
                    clipboardData: newData,
                    bubbles: true,
                    cancelable: true
                });
                target.dispatchEvent(pasteEvent);
            }
        }
    }, true);
})();