V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
infun
V2EX  ›  分享发现

篡改猴脚本:选中文本使用 Google 搜索按钮

  •  
  •   infun · 47 天前 · 623 次点击
    这是一个创建于 47 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用篡改猴脚本给网页上选中文本添加一个使用 Google 的搜索按钮

    // ==UserScript==
    // @name         搜索选中|Search Selection
    // @namespace    http://tampermonkey.net/
    // @version      1.2
    // @description  给选中文本添加一个使用 Google 的搜索按钮|Add a search button over selected text to search on Google
    // @author       INFUN 指挥智谱清言开发
    // @match        *://*/*
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        // 创建搜索按钮
        const searchButton = document.createElement('button');
        searchButton.style.cssText = `
            position: fixed;
            background-color: blue;
            color: white;
            padding: 3px 6px;
            border-radius: 15px;
            cursor: pointer;
            font-size: 12px;
            z-index: 9999;
            display: none;
        `;
        searchButton.textContent = '去搜索';
        document.body.appendChild(searchButton);
    
        // 处理选中文本
        document.addEventListener('mouseup', function() {
            const selection = window.getSelection();
            if (selection.rangeCount > 0 && selection.toString().trim() !== '') {
                const range = selection.getRangeAt(0);
                const rect = range.getBoundingClientRect();
                searchButton.style.top = `${rect.top - 30}px`;
                searchButton.style.left = `${rect.left + (rect.width / 2) - 35}px`;
                searchButton.style.display = 'block'; // 显示按钮
                searchButton.onclick = function() {
                    const query = encodeURIComponent(selection.toString());
                    window.open(`https://www.google.com/search?q=${query}&ie=utf-8&oe=utf-8&cr=countrySG`, '_blank');
                    searchButton.style.display = 'none'; // 隐藏按钮
                };
            } else {
                // 如果没有选中文本或选中的是空白,则隐藏按钮
                searchButton.style.display = 'none';
            }
        });
    
        // 点击非按钮区域或按下 Esc 键时隐藏按钮
        document.addEventListener('mousedown', function(event) {
            if (event.target !== searchButton) {
                searchButton.style.display = 'none';
            }
        });
    
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                searchButton.style.display = 'none';
            }
        });
    })();
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5303 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:26 · PVG 09:26 · LAX 18:26 · JFK 21:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.