// ==UserScript== // @name 网页文本翻译工具 // @namespace http://tampermonkey.net/ // @version 1.0 bate // @description 选中文本后右键翻译成中文 // @author Your name // @match *://*/* // @grant GM_xmlhttpRequest // @grant GM_addStyle // @license MIT // @downloadURL none // ==/UserScript== (function() { 'use strict'; // 添加样式 GM_addStyle(` .translation-popup { position: fixed; top: 10px; right: 10px; padding: 10px; background: white; border: 1px solid #ccc; border-radius: 4px; z-index: 10000; max-width: 300px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); } .translation-close { position: absolute; right: 5px; top: 5px; border: none; background: none; cursor: pointer; } `); // 创建右键菜单 document.addEventListener('contextmenu', function(event) { const selectedText = window.getSelection().toString().trim(); if (selectedText) { event.preventDefault(); const contextMenu = document.createElement('div'); contextMenu.className = 'translation-popup'; contextMenu.style.top = event.pageY + 'px'; contextMenu.style.left = event.pageX + 'px'; contextMenu.innerHTML = ''; document.body.appendChild(contextMenu); const menuItem = contextMenu.querySelector('.translation-menu-item'); menuItem.addEventListener('click', () => { translateText(selectedText); contextMenu.remove(); }); // 点击其他地方关闭菜单 document.addEventListener('click', function closeMenu() { contextMenu.remove(); document.removeEventListener('click', closeMenu); }); } }); function showTranslation(translatedText) { const div = document.createElement('div'); div.className = 'translation-popup'; div.textContent = translatedText; const closeButton = document.createElement('button'); closeButton.className = 'translation-close'; closeButton.textContent = '×'; closeButton.onclick = () => div.remove(); div.appendChild(closeButton); document.body.appendChild(div); setTimeout(() => div.remove(), 5000); } function translateText(text) { GM_xmlhttpRequest({ method: 'GET', url: `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=auto|zh`, onload: function(response) { try { const data = JSON.parse(response.responseText); if (data.responseStatus === 200) { showTranslation(data.responseData.translatedText); } } catch (error) { console.error('Translation error:', error); } }, onerror: function(error) { console.error('Request error:', error); } }); } })();