// ==UserScript== // @name Close Current Window // @namespace http://tampermonkey.net/ // @version 1.2 // @description 在任意页面添加红色关闭按钮,点击后立即关闭当前窗口 // @author Jack // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // 创建按钮 const button = document.createElement('button'); button.textContent = "X"; button.title = "点击立即关闭当前窗口"; // 按钮样式 - 红色警示风格 button.style.position = "fixed"; button.style.top = "15%"; button.style.right = "1%"; button.style.transform = "translateY(-50%)"; button.style.padding = "8px 12px"; button.style.fontSize = "14px"; button.style.fontWeight = "bold"; button.style.backgroundColor = "#ff4444"; button.style.color = "#fff"; button.style.border = "none"; button.style.borderRadius = "6px"; button.style.cursor = "pointer"; button.style.zIndex = "10000"; button.style.boxShadow = "0 2px 5px rgba(0,0,0,0.3)"; button.style.transition = "all 0.2s ease"; button.style.fontFamily = "Arial, sans-serif"; // 添加悬停效果 button.addEventListener('mouseover', () => { button.style.backgroundColor = "#ff0000"; button.style.boxShadow = "0 3px 8px rgba(0,0,0,0.4)"; }); button.addEventListener('mouseout', () => { button.style.backgroundColor = "#ff4444"; button.style.boxShadow = "0 2px 5px rgba(0,0,0,0.3)"; }); // 添加点击效果 button.addEventListener('mousedown', () => { button.style.backgroundColor = "#cc0000"; button.style.transform = "translateY(-50%) scale(0.95)"; }); button.addEventListener('mouseup', () => { button.style.backgroundColor = "#ff0000"; button.style.transform = "translateY(-50%) scale(1)"; }); // 点击事件 - 立即关闭当前窗口 button.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); // 立即尝试关闭窗口 try { // 首先尝试直接关闭 window.close(); // 如果1秒后窗口还没关闭,尝试备用方法 setTimeout(() => { if (!window.closed) { try { // 备用方法1:如果是通过window.open()打开的窗口 if (window.opener) { window.close(); } // 备用方法2:重定向到空白页 else { window.location.href = "about:blank"; // 如果重定向成功,按钮移除 button.remove(); } } catch (err) { console.log("关闭窗口尝试失败:", err); } } }, 1000); } catch (err) { console.log("关闭窗口出错:", err); // 如果出错,尝试重定向到空白页 window.location.href = "about:blank"; } }); // 挂载按钮到页面 document.body.appendChild(button); // 确保按钮在页面加载完成后始终存在 window.addEventListener('load', () => { if (!document.body.contains(button)) { document.body.appendChild(button); } }); })();