使用篡改猴脚本给网页上选中文本添加一个使用 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'; } }); })(); 