bob划词翻译

Show popup on text selection and trigger keyboard shortcut

当前为 2025-02-24 提交的版本,查看 最新版本

// ==UserScript==
// @name         bob划词翻译
// @namespace    https://github.com/jqtmviyu/UserScripts
// @version      0.2
// @description  Show popup on text selection and trigger keyboard shortcut
// @author       jqtmviyu
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @connect      localhost
// ==/UserScript==

;(function () {
  'use strict'

  let popup = null

  // 创建弹出提示
  function createPopup() {
    // console.log('创建弹出框')
    const div = document.createElement('div')
    div.textContent = 'B'
    div.style.cssText = `
            position: fixed;
            background: #333;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            z-index: 10000;
            font-size: 14px;
        `
    return div
  }


  // 清理选中和弹出框
  function cleanup() {
    // console.log('清理选中和弹出框')
    if (popup && popup.parentNode) {
      popup.parentNode.removeChild(popup)
    }
    window.getSelection().removeAllRanges()
  }

  // 监听选中文本事件
  document.addEventListener('mouseup', e => {
    const selection = window.getSelection()
    const selectedText = selection.toString().trim() // 获取选中的文本并去除空白

    // 检查是否在输入框或文本区域中
    const target = e.target
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
      return // 如果是在输入框或文本区域中,直接返回
    }

    // 如果有选中文本
    if (selectedText) {
      // 创建新的弹出框
      popup = createPopup()
      document.body.appendChild(popup)

      // 设置弹出框位置
      const rect = selection.getRangeAt(0).getBoundingClientRect()
      popup.style.left = `${rect.right}px`
      popup.style.top = `${rect.top - 30}px`

      // 点击弹出框发送请求
      popup.addEventListener('mousedown', e => {
        e.preventDefault()
        e.stopPropagation()
        GM_xmlhttpRequest({
          method: 'POST',
          url: 'http://localhost:8081/translate',
          headers: {
            'Content-Type': 'application/json'
          },
          data: JSON.stringify({ data: selectedText }),
          onload: function(response) {
            console.log('翻译请求已发送')
          },
          onerror: function(error) {
            console.error('请求失败:', error)
          }
        })
        cleanup()
      })
    } else {
      cleanup() // 如果没有选中文本,清理
    }
  })
})()

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址