// ==UserScript== // @name Outlook 邮箱广告清除器 // @name:en Outlook Fake-Mail Ads Remover // @namespace outlook-ad-block // @version 1.1.0 // @icon https://outlook.live.com/mail/favicon.ico // @description 彻底清除 Outlook 网页版伪装成邮件的广告块(含外层空白容器)、修正广告造成的虚假未读计数、隐藏右侧广告提示栏。不依赖随机类名,适配 SPA 与虚拟滚动。 // @author YOU-KNOW-WHO // @license MIT // @match *://outlook.live.com/* // @match *://*.outlook.live.com/* // @match *://outlook.office.com/* // @match *://outlook.office365.com/* // @match *://outlook.mail.microsoft.com/* // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_notification // @run-at document-start // ==/UserScript== /* * 解决的问题: * 1. 邮件列表里伪装成邮件的广告条目(广告 / Microsoft Outlook / 升级帐户) * 2. 隐藏后残留的外层容器空白块(.Ogt7j / .dOD_h / .jGG6V 等多层包装) * 3. 广告被计入"未读",导致文件夹树显示虚假的未读徽标 * 4. 右侧"你似乎正在使用广告阻止程序"广告栏与追踪像素 * * 识别依据(不依赖 OWA 每次构建都会变的随机类名): * - 广告头像:img[src*="ads-olk-icon"],与界面语言无关 * - 多语言广告标签文案(带二次校验,防止正文里的 "Ad" 被误杀) * - 右侧广告栏:c.live.com/c.gif 追踪像素、assets/ads/* 图标、"广告阻止程序" 文案 * - 未读徽标:[role="treeitem"] 的 title 与 "未读" 辅助文本 * * 定位方式:从特征节点向上冒泡,找【最小的一整行】(头像列与信息列是兄弟, * 发件人文本第一次出现的祖先即行根),再逐层向上隐藏"只含广告"的包装容器, * 直到遇到含真实邮件的列表容器为止 —— 空白块因此被彻底消除。 * 若容器内后来插入真实邮件,会自动恢复显示(自内向外处理)。 * * 处理策略默认 hide(display:none);菜单可切换 remove(物理删除)。 */ (function () { 'use strict'; // ------------------------------------------------------------------ // 配置 // ------------------------------------------------------------------ const KEY = 'oab_'; const DEFAULTS = { enabled: true, mode: 'hide', // hide = 隐藏(推荐,兼容 React 虚拟列表);remove = 从 DOM 移除 fixUnread: true, // 修正广告造成的虚假未读计数(显示层) hideSideAds: true, // 清除右侧广告提示栏 / 追踪像素 autoDismiss: false, // 模拟点击广告自带的"删除"按钮,可让服务端也减掉未读 pollInterval: 3000, // 兜底轮询(毫秒),0 表示关闭 debug: false, }; // 邮件列表广告 const AD_ICON = 'img[src*="ads-olk-icon"], img[src*="/images/ads-"]'; const AD_LABEL = /^(广告|广告邮件|Ads?|Advertisement|Sponsored|Anzeige|Werbung|Publicidad|Publicit[eé]|Pubblicit[aà]|Annuncio|広告|廣告|광고|Реклама|إعلان)$/i; const AD_SENDER = /Microsoft Outlook/i; const AD_EXTRA = /升级|高级功能|订阅|Premium|Upgrade|Subscribe/i; // 右侧广告栏 const SIDE_ICON = 'img[src*="c.live.com/c.gif"], img[src*="/assets/ads/"], img[src*="adbarmetrochoice"]'; const SIDE_TEXT = /广告阻止程序|无广告的 Outlook|广告选择|你似乎正在使用|ad blocker|ad-free outlook|ad choices/i; // 判断某段短文本是否"广告相关",用于安全地向上折叠容器 const ADISH_EXACT = /^(广告|广告邮件|Ads?|Advertisement|Sponsored|Microsoft Outlook|升级帐户|获取 Outlook 最新高级功能|广告选择|Ad choices|MO|删除|单击以查看详细信息|\d{1,2}:\d{2}(:\d{2})?)$/i; const ROW_MARK = 'data-oab-ad'; // 广告行 const BOX_MARK = 'data-oab-box'; // 广告外层包装(逐层隐藏) const PANEL_MARK = 'data-oab-panel'; // 右侧广告栏 const BADGE_MARK = 'data-oab-badge'; // 未读徽标 const CLICK_MARK = 'data-oab-dismissed'; const TITLE_RAW = 'data-oab-title-raw'; // React 给出的原始 title const TITLE_FIXED = 'data-oab-title-fixed'; // 脚本上次写入的 title const MAX_UP = 12; // 向上找行容器的最大层数 const MAX_CLIMB = 8; // 向上隐藏包装容器的最大层数 const DEBOUNCE = 80; // MutationObserver 合并扫描的延迟 const IS_TOP = (function () { try { return window.top === window; } catch (e) { return false; } })(); // ------------------------------------------------------------------ // 存储:优先 GM_*,降级 localStorage(兼容油猴 / 暴力猴 / 脚本猫) // ------------------------------------------------------------------ function read(k, d) { try { if (typeof GM_getValue === 'function') { const v = GM_getValue(KEY + k, d); return v === undefined || v === null ? d : v; } } catch (e) { /* 沙箱未注入该 API */ } try { const raw = localStorage.getItem(KEY + k); return raw === null ? d : JSON.parse(raw); } catch (e) { return d; } } const cfg = Object.assign({}, DEFAULTS, { enabled: read('enabled', true) !== false, mode: read('mode', 'hide') === 'remove' ? 'remove' : 'hide', fixUnread: read('fixUnread', true) !== false, hideSideAds: read('hideSideAds', true) !== false, autoDismiss: read('autoDismiss', false) === true, pollInterval: Number(read('pollInterval', DEFAULTS.pollInterval)) || 0, debug: read('debug', false) === true, }); function write(k, v) { cfg[k] = v; try { if (typeof GM_setValue === 'function') { GM_setValue(KEY + k, v); return; } } catch (e) { /* ignore */ } try { localStorage.setItem(KEY + k, JSON.stringify(v)); } catch (e) { /* ignore */ } } let blocked = 0; // 累计拦截的广告行 let panels = 0; // 累计清除的右侧广告栏 let dismissed = 0; // 累计模拟点击删除次数 let adSeen = 0; // 本页检测到的广告条数(用于修正未读,remove 后仍保留) let lastIcons = 0; function log() { if (cfg.debug) console.log.apply(console, ['%c[Outlook 广告清除器]', 'color:#0a6'].concat(Array.prototype.slice.call(arguments))); } function notice(msg) { console.info('%c[Outlook 广告清除器]', 'color:#0a6;font-weight:bold', msg); try { if (IS_TOP && typeof GM_notification === 'function') { GM_notification({ title: 'Outlook 广告清除器', text: msg, timeout: 3000 }); } } catch (e) { /* ignore */ } } // ------------------------------------------------------------------ // 通用工具 // ------------------------------------------------------------------ // 只放行"空文本"或精确匹配的广告短语;真实邮件的发件人/主题不会命中 function isAdish(text) { const t = (text || '').trim(); if (!t) return true; if (t.length > 40) return false; return ADISH_EXACT.test(t); } // 防止把整个邮件列表 / 主区域当成"一行" function isPlausibleRow(el) { if (!el || el === document.body || el === document.documentElement) return false; if ((el.textContent || '').trim().length > 200) return false; if (el.querySelectorAll('*').length > 200) return false; return true; } // 从广告特征节点向上找最小整行:头像列与信息列是兄弟, // 发件人文本第一次出现的祖先即为行根。 function findRow(seed) { let el = seed instanceof Element ? seed : (seed && seed.parentElement); let buttonAncestor = null; let depthAncestor = null; for (let i = 0; el && i < MAX_UP; i++, el = el.parentElement) { if (el === document.body || el === document.documentElement) break; if (el.hasAttribute(PANEL_MARK) || el.hasAttribute(BOX_MARK)) break; if (!isPlausibleRow(el)) break; if (AD_SENDER.test(el.textContent || '')) return el; if (!buttonAncestor && el.querySelector('button, [role="button"]')) buttonAncestor = el; if (i >= 8 && !depthAncestor) depthAncestor = el; } return buttonAncestor || depthAncestor; } function hide(el, mark) { if (!el.hasAttribute(mark)) el.setAttribute(mark, '1'); if (mark === ROW_MARK && cfg.mode === 'remove') { el.remove(); } else { el.style.setProperty('display', 'none', 'important'); el.setAttribute('aria-hidden', 'true'); } } function unhide(el, mark) { el.style.removeProperty('display'); el.removeAttribute('aria-hidden'); el.removeAttribute(mark); } // ------------------------------------------------------------------ // 广告块:隐藏整行 + 逐层向上隐藏纯广告包装(消除空白块) // ------------------------------------------------------------------ // 这是 1.1.0 的关键修复:旧版最多折叠 3 层外壳,剩下的 .Ogt7j 等 // 容器仍占高度,页面上就留下一个空白块。 function climbAndHide(row, fallbackParent) { let child = row; let el = row.parentElement || fallbackParent; for (let i = 0; i < MAX_CLIMB && el; i++) { if (el === document.body || el === document.documentElement) break; const text = (el.textContent || '').trim(); if (text.length > 600 || el.querySelectorAll('*').length > 500) break; const others = Array.prototype.slice.call(el.children).filter(function (c) { return c !== child && !c.hasAttribute(ROW_MARK) && !c.hasAttribute(BOX_MARK) && !c.hasAttribute(PANEL_MARK); }); // 这一层已经出现真实邮件或其它内容 —— 到此为止,绝不再向上隐藏 if (others.some(function (c) { return !isAdish(c.textContent); })) break; if (!el.hasAttribute(BOX_MARK)) hide(el, BOX_MARK); child = el; el = el.parentElement; } } // 容器内插入真实内容时恢复显示。必须自内向外: // querySelectorAll 是文档序(祖先在前),外层必须等内层处理完才能正确判断。 function refreshBoxes() { const boxes = Array.prototype.slice.call( document.querySelectorAll('[' + BOX_MARK + ']') ).reverse(); boxes.forEach(function (box) { const hasReal = Array.prototype.slice.call(box.children).some(function (c) { if (c.hasAttribute(ROW_MARK) || c.hasAttribute(BOX_MARK) || c.hasAttribute(PANEL_MARK)) return false; return !isAdish(c.textContent); }); if (hasReal) unhide(box, BOX_MARK); }); } function blockRow(seed, reason) { const row = findRow(seed); if (!row || row.hasAttribute(ROW_MARK) || row.hasAttribute(BOX_MARK) || row.hasAttribute(PANEL_MARK)) return false; if (!isPlausibleRow(row)) { log('候选容器过大,跳过:', row); return false; } const parent = row.parentElement; hide(row, ROW_MARK); blocked++; log('拦截广告(' + reason + '):', row); climbAndHide(row, parent); return true; } // 主通道:广告头像图标(最稳定) function scanIcons() { const imgs = document.querySelectorAll(AD_ICON); lastIcons = imgs.length; imgs.forEach(function (img) { if (img.closest('[' + ROW_MARK + '], [' + BOX_MARK + '], [' + PANEL_MARK + ']')) return; blockRow(img, '广告图标'); }); } // 只接受"邮件列表广告行里"的广告标签:标签向上 8 层内必须存在一个 // 同时含广告头像 + 微软发件人 + 操作按钮、且文本很短(<=120)的行容器。 // 右侧广告栏也有一个"广告"字样,靠这个校验挡住,避免把整个页面判成广告行。 function nearMailAdRow(label) { let el = label; for (let i = 0; el && i < 8; i++, el = el.parentElement) { if (el === document.body || el === document.documentElement) break; const text = (el.textContent || '').trim(); if (text.length > 120) break; if (el.querySelector(AD_ICON) && AD_SENDER.test(text) && el.querySelector('button, [title="删除"], [title="Delete"]')) return true; } return false; } // 兜底通道:多语言"广告"标签文案(低频执行,带二次校验防误杀) function scanLabels() { if (!document.body) return; const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, { acceptNode: function (node) { const text = (node.nodeValue || '').trim(); if (!text || text.length > 24 || !AD_LABEL.test(text)) return NodeFilter.FILTER_REJECT; const parent = node.parentElement; if (!parent || parent.children.length) return NodeFilter.FILTER_REJECT; if (parent.closest('[' + ROW_MARK + '], [' + BOX_MARK + '], [' + PANEL_MARK + ']')) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; }, }); const labels = []; let node; while ((node = walker.nextNode()) && labels.length < 30) labels.push(node.parentElement); labels.forEach(function (label) { if (!nearMailAdRow(label)) return; const row = findRow(label); if (!row || row.hasAttribute(ROW_MARK) || row.hasAttribute(BOX_MARK) || row.hasAttribute(PANEL_MARK)) return; if (!isPlausibleRow(row)) return; const text = row.textContent || ''; if (text.trim().length > 120) return; if (!AD_SENDER.test(text) && !row.querySelector(AD_ICON) && !AD_EXTRA.test(text)) return; const parent = row.parentElement; hide(row, ROW_MARK); blocked++; log('拦截广告(广告标签文案):', row); climbAndHide(row, parent); }); } // ------------------------------------------------------------------ // 右侧广告栏("你似乎正在使用广告阻止程序" + 广告选择 + 追踪像素) // ------------------------------------------------------------------ function findPanel(seed) { let best = null; let el = seed instanceof Element ? seed : (seed && seed.parentElement); for (let i = 0; el && i < 8; i++, el = el.parentElement) { if (el === document.body || el === document.documentElement) break; const text = (el.textContent || '').trim(); if (text.length > 260 || el.querySelectorAll('*').length > 100) break; if (el.querySelector('[role="treeitem"], [data-folder-name], [role="row"]')) break; if (SIDE_TEXT.test(text) && (el.querySelector(SIDE_ICON) || /广告选择|Ad choices/i.test(text))) { best = el; break; // 最小满足即停,不继续向上吞掉整个右侧栏 } } if (!best) return null; // 最多补掉一层空壳,避免残留空白;不再往上,防止波及其它右侧内容 const p = best.parentElement; if (p && p !== document.body && p !== document.documentElement && p.children.length === 1 && (p.textContent || '').trim().length <= 260 && p.querySelectorAll('*').length <= 110) { return p; } return best; } function scanSideAds(deep) { if (!cfg.hideSideAds || !document.body) return; const seeds = []; document.querySelectorAll(SIDE_ICON).forEach(function (img) { if (!img.closest('[' + PANEL_MARK + ']')) seeds.push(img); }); // 文案种子遍历全文,成本较高,只在启动 / 定时兜底时做; // 图标种子每轮都查,保证广告栏动态插入时也能及时清除。 if (deep) { const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, { acceptNode: function (node) { const text = (node.nodeValue || '').trim(); if (!text || text.length > 200 || !SIDE_TEXT.test(text)) return NodeFilter.FILTER_REJECT; const parent = node.parentElement; if (!parent || parent.closest('[' + PANEL_MARK + ']')) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; }, }); let node; while ((node = walker.nextNode()) && seeds.length < 20) seeds.push(node.parentElement); } seeds.forEach(function (seed) { if (seed.closest && seed.closest('[' + PANEL_MARK + ']')) return; const panel = findPanel(seed); if (!panel || panel === document.body || panel === document.documentElement) return; if (panel.hasAttribute(PANEL_MARK)) return; hide(panel, PANEL_MARK); panels++; log('清除右侧广告区域:', panel); }); } // ------------------------------------------------------------------ // 未读计数修正 // ------------------------------------------------------------------ function parseUnread(title) { const s = String(title || ''); const m = s.match(/(\d+)\s*(?:个\s*)?未读/) || s.match(/(\d+)\s+unread/i); return m ? Number(m[1]) : null; } function replaceUnread(title, n) { const s = String(title || ''); if (/(\d+)\s*(?:个\s*)?未读/.test(s)) return s.replace(/(\d+)\s*(?:个\s*)?未读/, n + ' 个未读'); if (/(\d+)\s+unread/i.test(s)) return s.replace(/(\d+)\s+unread/i, n + ' unread'); return s; } function isInboxItem(item, title) { const name = (item.getAttribute('data-folder-name') || '').trim(); return /^(收件箱|Inbox|受信トレイ|받은 편지함)$/i.test(name) || /^(收件箱|Inbox)\s*[-–—]/i.test(String(title || '').trim()); } function findBadge(item) { const label = Array.prototype.slice.call(item.querySelectorAll('span')).find(function (s) { return !s.children.length && /^(未读|unread)$/i.test((s.textContent || '').trim()); }); if (!label || !label.parentElement) return null; const badge = label.parentElement; const num = Array.prototype.slice.call(badge.children).find(function (c) { return !c.children.length && /^\d+$/.test((c.textContent || '').trim()); }); return num ? { num: num, holder: badge.parentElement || badge } : null; } function setBadge(item, n) { const b = findBadge(item); if (!b) return; const want = String(n); if (b.num.textContent.trim() !== want) b.num.textContent = want; if (n <= 0) { if (!b.holder.hasAttribute(BADGE_MARK)) hide(b.holder, BADGE_MARK); } else if (b.holder.hasAttribute(BADGE_MARK)) { unhide(b.holder, BADGE_MARK); } } function fixUnread() { if (!cfg.fixUnread || !cfg.enabled) return; document.querySelectorAll('[role="treeitem"][title], [data-folder-name][title]').forEach(function (item) { const current = item.getAttribute('title') || ''; if (!isInboxItem(item, current)) return; // React 若把 title 改回了服务器值,视为新的原始值,避免重复扣减 const fixed = item.getAttribute(TITLE_FIXED); if (!item.hasAttribute(TITLE_RAW) || (fixed !== null && current !== fixed)) { item.setAttribute(TITLE_RAW, current); } const orig = item.getAttribute(TITLE_RAW) || ''; const raw = parseUnread(orig); if (raw === null) return; const adjusted = Math.max(0, raw - adSeen); setBadge(item, adjusted); const next = replaceUnread(orig, adjusted); if (next !== current) { item.setAttribute('title', next); item.setAttribute(TITLE_FIXED, next); } }); } function restoreUnread() { document.querySelectorAll('[' + TITLE_RAW + ']').forEach(function (item) { const orig = item.getAttribute(TITLE_RAW) || ''; const raw = parseUnread(orig); if (raw !== null) setBadge(item, raw); item.setAttribute('title', orig); item.removeAttribute(TITLE_RAW); item.removeAttribute(TITLE_FIXED); }); } // 可选:模拟点击广告自带的"删除"按钮,让服务端也把广告从未读里移除。 // 默认关闭 —— 这是真正会操作邮箱的动作,需用户主动开启。 function autoDismissAds() { if (!cfg.autoDismiss) return; document.querySelectorAll('[' + ROW_MARK + ']').forEach(function (row) { if (row.hasAttribute(CLICK_MARK)) return; const btn = row.querySelector('[title="删除"], [title="Delete"], [aria-label="删除"], [aria-label="Delete"]'); if (!btn) return; row.setAttribute(CLICK_MARK, '1'); try { btn.click(); } catch (e) { log('点击删除按钮失败', e); } dismissed++; log('已模拟点击广告删除按钮'); }); } // ------------------------------------------------------------------ // 调度:MutationObserver + 节流 + 定时兜底 // ------------------------------------------------------------------ let timer = null; let wantDeep = false; function schedule(deep) { if (deep) wantDeep = true; if (timer) return; timer = setTimeout(function () { timer = null; const d = wantDeep; wantDeep = false; run(d); }, DEBOUNCE); } function run(deep) { if (!cfg.enabled) return; try { // 记录广告条数:以已拦截的广告行为准(避免同一行多个图标重复计数); // 物理移除后行已不在 DOM,用首次检出的图标数兜底,未读修正仍生效。 const icons = document.querySelectorAll(AD_ICON).length; const marked = document.querySelectorAll('[' + ROW_MARK + ']').length; const seenNow = marked || (icons > 0 ? 1 : 0); if (seenNow > adSeen) adSeen = Math.min(seenNow, 2); scanIcons(); scanSideAds(deep); // 先标记右侧广告栏,文案兜底才能安全排除它 if (deep) scanLabels(); refreshBoxes(); fixUnread(); if (deep) autoDismissAds(); } catch (e) { console.warn('[Outlook 广告清除器] 扫描异常:', e); } } function startObserver() { const mo = new MutationObserver(function (records) { for (let i = 0; i < records.length; i++) { const r = records[i]; if ((r.type === 'childList' && r.addedNodes.length) || r.type === 'attributes') { schedule(false); break; } } }); mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'], }); if (cfg.pollInterval > 0) { setInterval(function () { schedule(true); }, cfg.pollInterval); } } // ------------------------------------------------------------------ // 脚本猫菜单 // ------------------------------------------------------------------ let menuIds = []; function restorePanels() { document.querySelectorAll('[' + PANEL_MARK + ']').forEach(function (el) { unhide(el, PANEL_MARK); }); } function restoreAll() { document.querySelectorAll('[' + BOX_MARK + ']').forEach(function (el) { unhide(el, BOX_MARK); }); document.querySelectorAll('[' + ROW_MARK + ']').forEach(function (el) { unhide(el, ROW_MARK); }); restorePanels(); restoreUnread(); } function renderMenu() { if (typeof GM_registerMenuCommand !== 'function') return; const canUnregister = typeof GM_unregisterMenuCommand === 'function'; if (!canUnregister && menuIds.length) return; try { if (canUnregister) menuIds.forEach(function (id) { GM_unregisterMenuCommand(id); }); } catch (e) { /* ignore */ } menuIds = []; function add(text, fn) { try { menuIds.push(GM_registerMenuCommand(text, fn)); } catch (e) { /* ignore */ } } function toggle(key, label, after) { add(label + (cfg[key] ? ':开' : ':关'), function () { write(key, !cfg[key]); if (after) after(); schedule(true); renderMenu(); notice(label + '已' + (cfg[key] ? '开启' : '关闭')); }); } add(cfg.enabled ? '暂停拦截' : '恢复拦截', function () { write('enabled', !cfg.enabled); if (cfg.enabled) schedule(true); else restoreAll(); renderMenu(); notice(cfg.enabled ? '已恢复拦截' : '已暂停拦截'); }); add(cfg.mode === 'hide' ? '切换为「物理移除」' : '切换为「隐藏」', function () { const next = cfg.mode === 'hide' ? 'remove' : 'hide'; write('mode', next); if (next === 'remove') { document.querySelectorAll('[' + ROW_MARK + ']').forEach(function (el) { el.remove(); }); } schedule(true); renderMenu(); notice('处理方式已切换为:' + (next === 'hide' ? '隐藏(推荐)' : '物理移除')); }); toggle('fixUnread', '修正未读计数', function () { if (!cfg.fixUnread) restoreUnread(); }); toggle('hideSideAds', '清除右侧广告栏', function () { if (!cfg.hideSideAds) restorePanels(); }); toggle('autoDismiss', '自动点击广告删除按钮', function () { if (cfg.autoDismiss) notice('将模拟点击广告自带的删除按钮,可能影响服务端未读计数。'); }); add('输出拦截统计', function () { notice('累计拦截 ' + blocked + ' 个广告块 / 清除 ' + panels + ' 个广告栏 / 模拟删除 ' + dismissed + ' 次;本页广告 ' + adSeen + ' 条,当前检出 ' + lastIcons + ' 个图标。'); }); toggle('debug', '调试日志'); } // ------------------------------------------------------------------ // 启动(document-start 时 body 可能尚未出现) // ------------------------------------------------------------------ let booted = false; function init() { if (booted || !document.body) return; booted = true; if (IS_TOP) renderMenu(); startObserver(); schedule(true); if (IS_TOP) notice('已启动:清除广告块与空白容器、修正未读数、隐藏右侧广告栏。可在菜单中调整。'); log('当前配置:', cfg); } function boot() { if (!document.documentElement) { setTimeout(boot, 10); return; } if (document.body) { init(); return; } const wait = new MutationObserver(function () { if (document.body) { wait.disconnect(); init(); } }); wait.observe(document.documentElement, { childList: true }); } boot(); })();