编写Tampermonkey脚本实现检测指定img时自动关闭标签页
Tampermonkey(油猴)自动关闭标签页脚本
功能逻辑
- 页面加载完成后自动扫描表格行,检测指定位置是否存在目标图片
- 检测到src属性为
imgs/newmail.gif的目标图片时,自动关闭当前标签页 - 兼容内容延迟加载的页面,增加短周期轮询检测避免漏判
适配提示:根据你提供的页面代码片段,目标img实际位于每行第二个单元格(第一列为显示序号的单元格),如果首次运行脚本检测不到目标,把代码中
row.querySelector('td:first-child')替换为row.querySelector('td:nth-child(2)')即可完全匹配你给出的页面结构。
完整脚本代码
// ==UserScript== // @name 目标页面自动关闭 // @namespace localScript // @version 0.1 // @description 检测到新邮件标识图时自动关闭当前标签页 // @match *://*/* // @grant window.close // @run-at document-end // ==/UserScript== (function() { 'use strict'; // 目标元素检测逻辑 const hasTargetImg = () => { const tableRows = document.querySelectorAll('tr'); for (const row of tableRows) { // 默认匹配每行第一列,结构不符时按提示修改选择器 const firstCol = row.querySelector('td:first-child'); if (!firstCol) continue; const target = firstCol.querySelector('img[src="imgs/newmail.gif"]'); if (target) return true; } return false; }; // 页面加载完成后首次检测 if (hasTargetImg()) { window.close(); return; } // 动态内容轮询检测,每500ms扫描一次,最长检测10秒后自动停止,避免占用资源 let checkTimes = 0; const detectTimer = setInterval(() => { checkTimes++; if (hasTargetImg()) { clearInterval(detectTimer); window.close(); } if (checkTimes >= 20) clearInterval(detectTimer); }, 500); })();
使用说明
- 先安装Tampermonkey浏览器扩展,进入扩展的脚本管理页新建自定义脚本
- 把上述代码全选粘贴,覆盖脚本编辑页的默认模板内容
- 修改脚本头部的
@match字段,替换为你需要生效的具体页面地址规则(例如*://mail.example.com/*),避免脚本在无关页面运行 - 按前面的适配提示确认选择器和实际页面结构匹配
- 保存脚本后刷新目标页面即可生效
内容的提问来源于stack exchange,提问作者Владислав
相关产品推荐
相关产品推荐

