// ==UserScript==
// @name 高效文本文件查看器
// @namespace http://tampermonkey.net/
// @version 1.5
// @description 优化文本文件查看体验,支持快速复制、下载及长文本处理
// @author niweizhuan
// @match *://*/*
// @grant GM_addElement
// @grant GM_setClipboard
// @grant GM_download
// @license MIT
// @downloadURL none
// ==/UserScript==
(function() {
'use strict';
// 检测是否为纯文本文件
const isTextFile = window.location.pathname.toLowerCase().endsWith('.txt');
if (!isTextFile) {
return;
}
// 创建一个新的HTML页面
const newPage = `
文本文件查看器
加载失败,请检查链接是否正确。
`;
// 替换当前文档内容
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 });
})();