Greasy Fork

高效文本文件查看器

优化文本文件查看体验,支持快速复制、下载及长文本处理

目前为 2025-01-24 提交的版本。查看 最新版本

// ==UserScript==
// @name         高效文本文件查看器
// @namespace    http://tampermonkey.net/
// @version      1.5
// @description  优化文本文件查看体验,支持快速复制、下载及长文本处理
// @author       niweizhuan
// @match        *://*/*
// @grant        GM_addElement
// @grant        GM_setClipboard
// @grant        GM_download
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 检测是否为纯文本文件
    const isTextFile = window.location.pathname.toLowerCase().endsWith('.txt');

    if (!isTextFile) {
        return;
    }

    // 创建一个新的HTML页面
    const newPage = `
        <head>
            <title>文本文件查看器</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; background-color: #f0f0f0; }
                #header { margin-bottom: 20px; }
                #header button { margin-right: 10px; padding: 8px 16px; font-size: 14px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
                #header button:hover { background-color: #0056b3; }
                #content { white-space: pre-wrap; background-color: #f9f9f9; border: 1px solid #ddd; padding: 10px; border-radius: 4px; margin-top: 20px; font-family: monospace; font-size: 14px; }
                #error { color: red; font-weight: bold; margin-top: 20px; display: none; }
            </style>
        </head>
        <body>
            <div id="header">
                <button id="copyAll">复制全部</button>
                <button id="downloadText">下载文字</button>
            </div>
            <div id="content"></div>
            <div id="error">加载失败,请检查链接是否正确。</div>
        </body>
    `;

    // 替换当前文档内容
    document.documentElement.innerHTML = newPage;

    // 创建 Web Worker 来处理文本加载
    const worker = new Worker(URL.createObjectURL(new Blob([`
        self.onmessage = function(event) {
            const { url } = event.data;
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(textContent => {
                    self.postMessage({ success: true, textContent });
                })
                .catch(error => {
                    self.postMessage({ success: false, error: error.message });
                });
        };
    `], { type: 'text/javascript' })));

    // 监听 Web Worker 的消息
    worker.onmessage = function(event) {
        const { success, textContent, error } = event.data;
        const contentDiv = document.getElementById('content');
        const copyButton = document.getElementById('copyAll');
        const downloadButton = document.getElementById('downloadText');
        const errorDiv = document.getElementById('error');

        if (success) {
            contentDiv.textContent = textContent;

            // 如果文本过长,禁用复制按钮并提示用户下载
            if (textContent.length > 1000000) { // 假设超过1MB时提示下载
                copyButton.disabled = true;
                copyButton.textContent = '文本过长,无法复制';
                downloadButton.textContent = '下载文件';
            }

            // 添加按钮功能
            copyButton.addEventListener('click', () => {
                GM_setClipboard(textContent, { "type": "text" });
                alert('内容已复制到剪贴板!');
            });

            downloadButton.addEventListener('click', () => {
                GM_download({
                    url: window.location.href,
                    name: window.location.pathname.split('/').pop(),
                    confirm: false
                });
            });
        } else {
            alert('Failed to load text file:', error);
            errorDiv.style.display = 'block';
        }
    };

    // 向 Web Worker 发送消息,开始加载文本
    worker.postMessage({ url: window.location.href });
})();