// ==UserScript== // @name Seeyon OA Optimizer (自用版) // @namespace http://tampermonkey.net/ // @version 1.8.7.0 // @description 致远 OA 效能微调脚本。v1.8.7.0:新增「禁用自动登录默认账号」开关——开启后登录页切换器仅列出账号供手动选择、不再 5 秒倒计时自动登录;账户管理升级——按域名(host)隔离多企业/多账号,新增账户管理器弹窗(设默认/删除/恢复询问/精准清空)与登录页迷你切换器(默认账号预选、5 秒倒计时自动登录);新账号登录成功后询问保存、拒绝则记为「不保存」不再询问;旧版单套账密首次运行自动迁移;悬浮控制台按「登录与账户 / 界面与交互 / 缓存与网络」三类归类;v1.8.6.7:新增「屏蔽掉线弹窗」开关——劫持 alert 拦截「被迫下线,原因:与服务器失去连接」等 WebSocket 掉线提示;v1.8.6.6:新增「自动注销已登录占用」开关——登录页出现「同一窗口中不能登录多个用户」时自动点击「注销」释放占用;v1.8.6.5:新增「自动打开转办意见」开关;v1.8.6.4:控制台边缘磁吸形态再优化。 // @author LBCN // @match *://*/seeyon/* // @license MIT // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_registerMenuCommand // @grant unsafeWindow // @run-at document-start // ==/UserScript== (function() { 'use strict'; const _win = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; // 1. 开关与菜单 const getSetting = (k) => GM_getValue(k, true), setSetting = (k, v) => GM_setValue(k, v); let cacheHits = 0, cacheSavedBytes = 0; // 0ms 缓存命中统计(控制台角标/面板展示) // 顶帧判定:仅顶帧构建控制台;内嵌子帧的命中数据经 postMessage 汇总到顶帧 const isTopFrame = (() => { try { return _win.top === _win.self; } catch (e) { return false; } })(); const reportHit = (bytes) => { cacheHits++; cacheSavedBytes += bytes || 0; if (!isTopFrame) { try { _win.top.postMessage({ __myoa: 'hit', hits: 1, bytes: bytes || 0 }, _win.location.origin); } catch (e) {} } }; if (isTopFrame) window.addEventListener('message', (e) => { if (e.origin !== _win.location.origin || !e.data || e.data.__myoa !== 'hit') return; cacheHits += e.data.hits || 0; cacheSavedBytes += e.data.bytes || 0; }); const regToggle = (k, label) => GM_registerMenuCommand(`${getSetting(k) ? "✅" : "❌"} | ${label}`, () => { setSetting(k, !getSetting(k)); _win.location.reload(); }); regToggle('opt_title_block', "屏蔽标题闪烁"); regToggle('opt_force_tab', "强制新标签页打开"); regToggle('opt_block_leave', "屏蔽离开网站确认"); regToggle('opt_auto_login', "自动保存账密登录"); regToggle('opt_ui_perf', "UI加速与正文全屏"); regToggle('opt_web_cache', "网页终极缓存 (0ms)"); regToggle('opt_auto_turn', "自动打开转办意见"); regToggle('opt_auto_logout', "自动注销已登录占用"); regToggle('opt_no_auto_login', "禁用自动登录默认账号"); regToggle('opt_block_offline', "屏蔽掉线弹窗"); GM_registerMenuCommand("👤 打开账户管理器", () => openAccountManager()); GM_registerMenuCommand("🗑️ 清空终极缓存库", () => { if (_win.indexedDB) _win.indexedDB.deleteDatabase('UltimateWebCache_v3'); localStorage.removeItem('uwc_tracker'); alert("缓存已清空!"); _win.location.reload(); }); // 2. 标题防闪烁:严格整词定界,避免误伤单位系统全称 if (getSetting('opt_title_block')) { try { const doc = _win.document, docProto = _win.Document?.prototype || Document.prototype; const origDesc = Object.getOwnPropertyDescriptor(docProto, 'title'), blinkRegex = /^【?\s*(A8\+|A8-N|A8N)\s*】?$/i; if (origDesc?.set) Object.defineProperty(doc, 'title', { set(v) { if (!blinkRegex.test(String(v || '').trim())) origDesc.set.call(this, v); }, get() { return origDesc.get.call(this); }, configurable: true }); } catch (e) {} } // 3. 强制新标签页打开 if (getSetting('opt_force_tab')) { try { const origOpen = _win.open; _win.open = function(...args) { if (args[2]) args[2] = null; return origOpen.apply(this, args); }; } catch (e) {} } // 4. 核心样式注入 const injectStyles = (doc) => { if (!doc || doc.getElementById('myoa-opt-style')) return; const doInject = () => { const t = doc.head || doc.documentElement; if (!t || doc.getElementById('myoa-opt-style')) return; const s = doc.createElement('style'); s.id = 'myoa-opt-style'; s.innerHTML = ` * { animation: none !important; transition: none !important; } .V83WorkbenchGuide-warp, #messageBlockMask, #ai-assist-root-bangs, #imt-webext { display: none !important; } .myoa-maximized { top: 0 !important; left: 0 !important; width: 100vw !important; height: 100vh !important; } .myoa-maximized .layui-layer-content { height: calc(100vh - 45px) !important; padding: 0 !important; overflow: hidden !important; } .myoa-maximized iframe { height: 100% !important; width: 100% !important; } .common_table tbody tr:hover, .flexigrid tbody tr:hover, .grid_container tbody tr:hover { background-color: #f0f7ff !important; } #content_deal_comment { height: 100px !important; resize: vertical !important; } /* 常用语卡片:落入批注框后撑满宽度;框外保留 290px 兜底 */ .comlanguage, [class*="comlanguage"] { width: 290px !important; min-width: 0 !important; box-sizing: border-box !important; z-index: 2500 !important; box-shadow: 0 8px 24px rgba(0,0,0,0.18) !important; border-radius: 6px !important; overflow: visible !important; } #content_deal_comment_div .comlanguage { position: absolute !important; top: 100% !important; left: 0 !important; width: 100% !important; height: auto !important; z-index: 2000 !important; box-shadow: 0 8px 16px rgba(0,0,0,0.15) !important; border: 1px solid #dce0e3 !important; border-radius: 4px !important; } .comlanguage .comLanguage_close { display: block !important; cursor: pointer !important; } .comlanguage_list, .comLanguage_list, [class*="comlanguage_list"] { height: auto !important; min-height: 160px !important; max-height: 280px !important; overflow-y: auto !important; } /* 弹层提至 9999 并自适应宽度;仅命中浮层类,避免误伤底部"请选择"触发器 */ .el-select-dropdown, .el-popper, [class*="el-select-dropdown"], [class*="el-popper"], .common_drop_list_content, [class*="drop_list_content"], .dropdown_content_iframe { z-index: 9999 !important; width: auto !important; min-width: 92px !important; } .el-select-dropdown__item, .checkBoxLabel, .checkbox_span { white-space: nowrap !important; } /* 附件区穿透多层父容器解除定宽,显示完整文件名 */ .file-list-container { display: flex !important; flex-wrap: wrap !important; height: auto !important; overflow: visible !important; gap: 8px 14px !important; } .file-list-container .item-wrapper, .file-list-container .left-item-wrapper, .file-list-container .title-wrapper, .file-list-container .name-element-container, .file-list-container .name-wrapper, .file-list-container .download-att-container, .file-list-container .download-att-wrapper, .file-list-container .flex-wrapper, .file-list-container .filename, .att_name, .file_name, .attachment_name { max-width: none !important; width: auto !important; overflow: visible !important; white-space: nowrap !important; text-overflow: clip !important; display: inline-flex !important; align-items: center !important; flex: 0 0 auto !important; } `; t.appendChild(s); }; if (doc.head || doc.documentElement) doInject(); else doc.addEventListener('DOMContentLoaded', doInject, { once: true }); }; if (getSetting('opt_ui_perf')) injectStyles(document); // 5. 屏蔽离开网站确认与废弃 unload if (getSetting('opt_block_leave')) { try { _win.onbeforeunload = null; Object.defineProperty(_win, 'onbeforeunload', { get: () => null, set: () => {}, configurable: true }); _win.onunload = null; Object.defineProperty(_win, 'onunload', { get: () => null, set: () => {}, configurable: true }); const origAEL = _win.addEventListener; _win.addEventListener = function(t, l, o) { if (t === 'beforeunload' || t === 'unload') return; return origAEL.apply(this, arguments); }; } catch (e) {} } // 5.1 屏蔽掉线弹窗:WebSocket 断链时 Seeyon 会 alert「被迫下线…」,原生弹窗无法程序关闭,改为直接吞掉 if (getSetting('opt_block_offline')) { try { const origAlert = _win.alert; _win.alert = function(msg) { const s = String(msg == null ? '' : msg); if (/被迫下线|与服务器失去连接/.test(s)) { console.log(`%c[OA优化] 已拦截掉线弹窗: ${s}`, 'color:#ff8c00;font-weight:bold;'); return; } return origAlert.apply(this, arguments); }; } catch (e) {} } // 6. 多域名账户管理 const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&':'&','<':'<','>':'>','"':'"' }[c])); const ACCOUNTS_KEY = 'myoa_accounts'; const getHost = () => { try { return _win.location.host || 'unknown'; } catch (e) { return 'unknown'; } }; let _acctCache = null; // ponytail: 内存缓存,避免每次都 JSON.parse 整库 const loadAccounts = () => { if (_acctCache) return _acctCache; try { return (_acctCache = JSON.parse(GM_getValue(ACCOUNTS_KEY, '{}')) || {}); } catch (e) { return {}; } }; const saveAccounts = (obj) => { try { _acctCache = obj; GM_setValue(ACCOUNTS_KEY, JSON.stringify(obj)); } catch (e) {} }; const getDomain = (host) => { const a = loadAccounts(); return a[host] || { accounts: [], skipSave: [] }; }; const setDomain = (host, data) => { const a = loadAccounts(); a[host] = data; saveAccounts(a); }; const findAccount = (d, user) => d.accounts.find(x => x.user === user); const getDefault = (d) => d.accounts.find(x => x.isDefault) || d.accounts[0] || null; const addAccount = (host, user, pass, setDefault) => { const d = getDomain(host); let acc = findAccount(d, user); if (acc) acc.pass = pass; else { acc = { user, pass, isDefault: false }; d.accounts.push(acc); } if (setDefault || d.accounts.length === 1) d.accounts.forEach(x => x.isDefault = (x === acc)); setDomain(host, d); return acc; }; const removeAccount = (host, user) => { const d = getDomain(host); d.accounts = d.accounts.filter(x => x.user !== user); if (d.accounts.length && !d.accounts.some(x => x.isDefault)) d.accounts[0].isDefault = true; setDomain(host, d); }; const setDefaultAccount = (host, user) => { const d = getDomain(host); d.accounts.forEach(x => x.isDefault = (x.user === user)); setDomain(host, d); }; const addSkip = (host, user) => { const d = getDomain(host); if (!d.skipSave.includes(user)) d.skipSave.push(user); setDomain(host, d); }; const removeSkip = (host, user) => { const d = getDomain(host); d.skipSave = d.skipSave.filter(x => x !== user); setDomain(host, d); }; const clearDomain = (host) => { const a = loadAccounts(); delete a[host]; saveAccounts(a); }; const clearAllAccounts = () => saveAccounts({}); // 旧版单套凭据迁移:首次运行把 myoa_username/myoa_password 并入当前域名并设为默认 (function migrateOldCreds() { const u = GM_getValue('myoa_username', ''), p = GM_getValue('myoa_password', ''); if (!u) return; addAccount(getHost(), u, p, true); GM_deleteValue('myoa_username'); GM_deleteValue('myoa_password'); })(); // 登录失败自愈:提示清空该域名旧密码 const handleLoginError = (doc, u, p) => { const err = doc.getElementById('login_error'); if (err && err.style.display !== 'none' && err.textContent.trim() && !window._myoa_err) { window._myoa_err = true; if (confirm(`登录失败:【${err.textContent.trim()}】\n是否清空本地该域名的旧密码?`)) { const d = getDomain(getHost()); if (findAccount(d, u.value)) removeAccount(getHost(), u.value); u.value = ''; p.value = ''; u.focus(); } } }; // 填表并触发登录(复用 Seeyon 自身登录按钮,兼容隐私勾选/验证码) const doFillAndLogin = (doc, u, p, b, acc) => { window._myoa_logined = true; u.value = acc.user; p.value = acc.pass; u.dispatchEvent(new Event('input', { bubbles: true })); p.dispatchEvent(new Event('input', { bubbles: true })); const pc = doc.getElementById('privacyCheck'); if (pc && !pc.checked) { pc.checked = true; pc.dispatchEvent(new Event('change', { bubbles: true })); } const vDiv = doc.getElementById('verifyCodeDiv'); if (!vDiv || vDiv.style.display === 'none') setTimeout(() => b.click(), 500); }; // 新账号登录成功后询问保存;拒绝则记为「不保存」以后不再询问 const maybePromptSave = (host, user, pass) => { if (!getSetting('opt_auto_login')) return; const d = getDomain(host); if (findAccount(d, user) || d.skipSave.includes(user)) return; if (confirm(`是否将账号「${user}」保存到账户管理器(域名 ${host})?\n取消则以后不再询问该账号。`)) addAccount(host, user, pass, d.accounts.length === 0); else addSkip(host, user); }; const attachLoginCapture = (doc, u, p, b) => { if (window._myoa_capture) return; window._myoa_capture = true; const capture = () => { const user = u.value, pass = p.value; if (!user || !pass) return; const pd = { host: getHost(), user, pass }; setTimeout(() => { const err = doc.getElementById('login_error'); if (err && err.style.display !== 'none' && err.textContent.trim()) return; // 失败不保存 maybePromptSave(pd.host, pd.user, pd.pass); }, 2500); }; b.addEventListener('click', capture); p.addEventListener('keydown', (e) => { if (e.key === 'Enter') capture(); }); }; // 登录页迷你切换器:列出当前域名账号,默认预选,5 秒倒计时自动登录默认账号 const showMiniSwitcher = (doc, host, d, u, p, b) => { if (window._myoa_switcherShown || window._myoa_switcherManual || !doc.body) return; const def = getDefault(d); if (!def) return; const autoLogin = !getSetting('opt_no_auto_login'); // 禁用自动登录默认账号时仅手动选择 window._myoa_switcherShown = true; const box = doc.createElement('div'); box.id = 'myoa-switcher'; let remain = 5, timer = null; const render = () => { box.innerHTML = `
选择登录账号 ${esc(host)}
` + `
${autoLogin ? remain + 's 后自动登录默认账号' : '请手动选择账号登录'}
` + d.accounts.map(a => `
${esc(a.user)}${a.isDefault ? ' 默认' : ''}
`).join('') + `
`; box.querySelectorAll('.acc').forEach(el => el.onclick = () => { clearInterval(timer); doFillAndLogin(doc, u, p, b, findAccount(d, el.dataset.u)); box.remove(); window._myoa_switcherShown = false; }); box.querySelector('.manual').onclick = () => { clearInterval(timer); box.remove(); window._myoa_switcherShown = false; window._myoa_switcherManual = true; }; box.querySelector('.mgr').onclick = () => openAccountManager(); }; render(); doc.body.appendChild(box); if (autoLogin) timer = setInterval(() => { remain--; if (remain <= 0) { clearInterval(timer); doFillAndLogin(doc, u, p, b, def); box.remove(); window._myoa_switcherShown = false; } else { const c = box.querySelector('.cnt'); if (c) c.textContent = remain + 's 后自动登录默认账号'; } }, 1000); }; // 账户管理器弹窗 function openAccountManager() { if (document.getElementById('myoa-am-overlay')) return; if (!document.getElementById('myoa-am-style')) { const s = document.createElement('style'); s.id = 'myoa-am-style'; s.textContent = ` #myoa-am-overlay { position: fixed; inset: 0; z-index: 2147483647; background: rgba(0,0,0,.45); display: flex; align-items: center; justify-content: center; font: 13px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif; } .am { width: 420px; max-width: 92vw; max-height: 80vh; display: flex; flex-direction: column; background: #fff; border-radius: 12px; box-shadow: 0 16px 48px rgba(0,0,0,.3); overflow: hidden; } .am-h { padding: 12px 14px; font-weight: 600; background: linear-gradient(180deg,#1677ff,#0c5fd6); color: #fff; display: flex; justify-content: space-between; align-items: center; } .am-close { cursor: pointer; font-size: 18px; line-height: 1; } .am-b { padding: 8px 14px; overflow-y: auto; } .am-empty { color: #999; padding: 20px; text-align: center; } .am-host { font-weight: 600; color: #1677ff; margin: 10px 0 4px; } .am-hostops { margin: 2px 0 6px; } .am-hostops a, .am-ops a { color: #1677ff; cursor: pointer; margin-right: 10px; text-decoration: none; } .am-hostops a { color: #ff4d4f; font-size: 12px; } .am-acc { display: flex; justify-content: space-between; align-items: center; padding: 6px 8px; border-radius: 6px; background: #f6f8fb; margin: 4px 0; } .am-acc.skip { background: #fff7e6; } .am-acc em { color: #c98a2e; font-style: normal; font-size: 11px; } .am-def { color: #389e0d; font-size: 11px; margin-left: 6px; } .am-f { padding: 10px 14px; border-top: 1px solid #eee; display: flex; gap: 8px; } .am-f button { flex: 1; padding: 7px 0; border: 1px solid #eee; border-radius: 6px; background: #fafafa; color: #444; cursor: pointer; } .am-f button:hover { border-color: #1677ff; color: #1677ff; } `; (document.head || document.documentElement).appendChild(s); } const ov = document.createElement('div'); ov.id = 'myoa-am-overlay'; ov.innerHTML = '
账户管理器×
'; const body = ov.querySelector('.am-b'); const render = () => { const all = loadAccounts(), hosts = Object.keys(all); if (!hosts.length) { body.innerHTML = '
暂无保存的账户
'; return; } let html = ''; hosts.forEach(host => { const d = all[host]; html += `
🌐 ${esc(host)}
`; d.accounts.forEach(a => { html += `
${esc(a.user)}${a.isDefault ? '默认' : ''}` + `设默认删除
`; }); (d.skipSave || []).forEach(u => { html += ``; }); html += `
清空该域名全部
`; }); body.innerHTML = html; body.querySelectorAll('a[data-act]').forEach(a => a.onclick = () => { const h = a.dataset.h, u = a.dataset.u, act = a.dataset.act; if (act === 'def') setDefaultAccount(h, u); else if (act === 'del') removeAccount(h, u); else if (act === 'unskip') removeSkip(h, u); else if (act === 'delhost') { if (confirm(`确认清空域名 ${h} 的全部账户?`)) clearDomain(h); } render(); }); }; render(); ov.querySelector('.am-close').onclick = () => ov.remove(); ov.querySelector('.am-add').onclick = () => { const h = prompt('域名(host,如 106.38.198.86:8080):', getHost()); if (!h) return; const u = prompt('账号:'); if (!u) return; const p = prompt('密码:'); if (p === null) return; addAccount(h.trim(), u.trim(), p, false); render(); }; ov.querySelector('.am-clearall').onclick = () => { if (confirm('确认清空全部已保存账户?')) { clearAllAccounts(); render(); } }; ov.addEventListener('click', (e) => { if (e.target === ov) ov.remove(); }); document.body.appendChild(ov); } // 6.0 自动登录(按域名分发) const handleAutoLogin = (doc = document) => { if (!getSetting('opt_auto_login')) return; const u = doc.getElementById('login_username'), p = doc.getElementById('login_password1'), b = doc.getElementById('login_button'); if (!u || !p) return; handleLoginError(doc, u, p); if (window._myoa_logined || !b) return; const host = getHost(), d = getDomain(host); attachLoginCapture(doc, u, p, b); if (d.accounts.length === 0) return; // 无保存账号:走手动登录 + 成功后询问保存 showMiniSwitcher(doc, host, d, u, p, b); }; // 6.1 登录页「已登录占用」自动注销:出现「同一窗口中不能登录多个用户」时自动点击注销 const handleAutoLogout = (doc) => { if (!getSetting('opt_auto_logout') || window._myoa_autoLoggedOut) return; const la = doc && doc.getElementById('loggedArea'); if (!la) return; // 仅在提示可见时处理(某些模板默认隐藏,登录占用时才显示) let disp = la.style.display; try { const cs = la.ownerDocument.defaultView.getComputedStyle(la); if (cs) disp = cs.display; } catch (e) {} if (disp === 'none') return; if (!/同一窗口中不能登录多个用户/.test(la.textContent || '')) return; const logout = la.querySelector('a[href*="method=logout"]'); if (logout) { window._myoa_autoLoggedOut = true; console.log('%c[OA优化] 检测到同一窗口已登录占用,自动点击「注销」释放', 'color:#ff8c00;font-weight:bold;'); logout.click(); } }; // 7. 核心优化执行 const executeOptimizations = () => { const autoLogin = getSetting('opt_auto_login'), autoLogout = getSetting('opt_auto_logout'), uiPerf = getSetting('opt_ui_perf'), autoTurn = getSetting('opt_auto_turn'); if (autoLogin) handleAutoLogin(document); if (autoLogout) handleAutoLogout(document); if (uiPerf) { ['htmlFrame_main', 'officeTransDialog_main'].forEach(id => { const f = document.getElementById(id), l = f?.closest('.layui-layer'); if (l && !l.classList.contains('myoa-maximized')) { l.classList.add('myoa-maximized'); _win.dispatchEvent(new Event('resize')); try { f.contentWindow?.dispatchEvent(new Event('resize')); } catch (e) {} } }); } // 单趟 iframe 扫描:自动注销 + 业务帧样式注入(合并两次查询) document.querySelectorAll('iframe').forEach(f => { try { const cd = f.contentDocument; if (!cd) return; if (autoLogout) handleAutoLogout(cd); if ((f.id === 'zwIframe' || f.id.startsWith('layui-layer-iframe')) && !f.dataset.myoaInjected) { injectStyles(cd); f.dataset.myoaInjected = 'true'; } } catch (e) {} }); // 常用语卡片兜底:若未处于批注框内则移入,确保 width:100% 生效 const cDiv = document.getElementById('content_deal_comment_div'); if (cDiv) { const cl = document.querySelector('.comlanguage'); if (cl && cl.parentNode !== cDiv) cDiv.appendChild(cl); if (cDiv.offsetParent !== null && !window._myoa_cpClicked) { window._myoa_cpClicked = true; if (!(/govdoc/i.test(_win.location.href) || document.title.includes('发文稿纸'))) document.getElementById('cphrase')?.click(); } } // 自动打开公文「转办意见」:被转办时顶部出现的转办意见按钮,自动点击展开 if (autoTurn) { const turnBtn = document.getElementById('turnRecEdocInfoDetails1'); if (turnBtn && !window._myoa_turnOpened && typeof _win.showTurnRecEdocInfo2 === 'function') { try { turnBtn.click(); window._myoa_turnOpened = true; } catch (e) {} } } }; // 8. 终极网页缓存 (0ms):拦截 fetch 与 XMLHttpRequest,命中即本地返回 if (getSetting('opt_web_cache')) { const CACHE_TTL = 10 * 60 * 1000, mem = new Map(); let db = null; const dbP = new Promise(res => { const r = indexedDB.open('UltimateWebCache_v3', 1); r.onupgradeneeded = (e) => e.target.result.createObjectStore('cache', { keyPath: 'url' }); r.onsuccess = (e) => { db = e.target.result; db.transaction('cache', 'readonly').objectStore('cache').getAll().onsuccess = (ev) => { ev.target.result.forEach(i => mem.set(i.url, i)); res(); }; }; r.onerror = () => res(); }); const cleanKey = (u) => { try { const url = new URL(u, _win.location.href); ['CSRFTOKEN', '_sessionid', 'random', '_', '_t', 'ts', 'timestamp', 'v', 't'].forEach(k => url.searchParams.delete(k)); return url.href; } catch (e) { return u; } }; // 仅缓存静态资源与 cssData 响应 const shouldCache = (abs) => /\.(?:js|css|png|jpe?g|woff2?|ttf|svg)(?:\?.*)?$/i.test(abs) || abs.includes('method=cssData'); // 首次命中即写入 IndexedDB(去噪键已保证为重复资源;10 分钟 TTL 限流) const storeInCache = (k, buf, ct) => { const tr = JSON.parse(localStorage.getItem('uwc_tracker') || '{}'); tr[k] = (tr[k] || 0) + 1; if (tr[k] >= 1) { db?.transaction('cache', 'readwrite').objectStore('cache').put({ url: k, content: buf, contentType: ct, cachedTime: Date.now() }); mem.set(k, { url: k, content: buf, contentType: ct, cachedTime: Date.now() }); delete tr[k]; } localStorage.setItem('uwc_tracker', JSON.stringify(tr)); }; const logHit = (k) => console.log(`%c[缓存命中 0ms] ${k}`, 'color:#9C27B0;font-weight:bold;'); // 8.1 拦截 fetch const origFetch = _win.fetch; _win.fetch = async function(input, init) { await dbP; const abs = new URL(typeof input === 'string' ? input : input.url, _win.location.href).href; const method = (init && init.method ? String(init.method).toUpperCase() : 'GET'); if (method !== 'GET' || !shouldCache(abs)) return origFetch.apply(this, arguments); const k = cleanKey(abs), m = mem.get(k); if (m && Date.now() - m.cachedTime < CACHE_TTL) { logHit(k); reportHit(m.content.byteLength); return new Response(m.content, { headers: { 'Content-Type': m.contentType } }); } const res = await origFetch.apply(this, arguments); if (res.status === 200) { const buf = await res.clone().arrayBuffer(); storeInCache(k, buf, res.headers.get('Content-Type') || ''); } return res; }; // 8.2 拦截 XMLHttpRequest,命中时模拟响应回填 const decodeText = (buf) => new TextDecoder('utf-8').decode(buf); const buildMockResponse = (xhr, item) => { let body; switch (xhr.responseType) { case 'arraybuffer': body = item.content; break; case 'blob': body = new Blob([item.content], { type: item.contentType }); break; case 'json': try { body = JSON.parse(decodeText(item.content)); } catch (e) { body = null; } break; default: body = decodeText(item.content); } Object.defineProperty(xhr, 'status', { get: () => 200, configurable: true }); Object.defineProperty(xhr, 'statusText', { get: () => 'OK', configurable: true }); Object.defineProperty(xhr, 'readyState', { get: () => 4, configurable: true }); Object.defineProperty(xhr, 'response', { get: () => body, configurable: true }); Object.defineProperty(xhr, 'responseText', { get: () => (typeof body === 'string' ? body : decodeText(item.content)), configurable: true }); xhr.getResponseHeader = (h) => (String(h).toLowerCase() === 'content-type' ? item.contentType : null); xhr.getAllResponseHeaders = () => `content-type: ${item.contentType}\r\n`; }; const mockXHR = (xhr, item) => { buildMockResponse(xhr, item); setTimeout(() => { xhr.dispatchEvent(new Event('readystatechange')); xhr.dispatchEvent(new Event('load')); }, 0); }; const origXHROpen = _win.XMLHttpRequest.prototype.open; const origXHRSend = _win.XMLHttpRequest.prototype.send; _win.XMLHttpRequest.prototype.open = function(method, url, ...rest) { this._myoa_method = String(method || 'GET').toUpperCase(); this._myoa_url = typeof url === 'string' ? url : (url && url.toString()); return origXHROpen.apply(this, arguments); }; _win.XMLHttpRequest.prototype.send = function(...args) { const self = this; let abs; try { abs = new URL(self._myoa_url, _win.location.href).href; } catch (e) { abs = self._myoa_url; } if (self._myoa_method === 'GET' && shouldCache(abs)) { const k = cleanKey(abs), m = mem.get(k); if (m && Date.now() - m.cachedTime < CACHE_TTL) { logHit(k); reportHit(m.content.byteLength); mockXHR(self, m); return; } self.addEventListener('load', async function() { if (self.status !== 200) return; let buf = null; try { if (self.responseType === 'arraybuffer') buf = self.response; else if (self.responseType === 'blob') buf = await self.response.arrayBuffer(); else buf = new TextEncoder().encode(self.responseText).buffer; } catch (e) { return; } if (buf) storeInCache(k, buf, self.getResponseHeader('Content-Type') || ''); }); } return origXHRSend.apply(this, args); }; } // 9. 挂载执行(60ms 防抖,抑制 DOM 突变风暴) window.addEventListener('DOMContentLoaded', executeOptimizations); let timer = null; const observer = new MutationObserver(() => { if (timer) clearTimeout(timer); timer = setTimeout(executeOptimizations, 60); }); window.addEventListener('load', () => { if (document.body) observer.observe(document.body, { childList: true, subtree: true }); }); // 10. 左下角控制台:快速开关 + 缓存统计 // 开关元数据:needReload=true 的项仅在 document-start 阶段安装钩子, // 运行时改 GM 值不会卸载已装钩子,须在面板内切换后刷新页面才能生效(标签后标「需刷新」)。 const SETTINGS_META = [ { cat: '登录与账户', key: 'opt_auto_login', label: '自动保存账密登录', needReload: false, hint: '下次登录生效' }, { cat: '登录与账户', key: 'opt_no_auto_login', label: '禁用自动登录默认账号', needReload: false, hint: '切换器不自动登' }, { cat: '登录与账户', key: 'opt_auto_logout', label: '自动注销已登录占用', needReload: false, live: true }, { cat: '界面与交互', key: 'opt_title_block', label: '屏蔽标题闪烁', needReload: true, hint: '需刷新' }, { cat: '界面与交互', key: 'opt_force_tab', label: '强制新标签页打开', needReload: true, hint: '需刷新' }, { cat: '界面与交互', key: 'opt_block_leave', label: '屏蔽离开网站确认', needReload: true, hint: '需刷新' }, { cat: '界面与交互', key: 'opt_ui_perf', label: 'UI加速与正文全屏', needReload: false, live: true }, { cat: '界面与交互', key: 'opt_auto_turn', label: '自动打开转办意见', needReload: false, live: true }, { cat: '缓存与网络', key: 'opt_web_cache', label: '网页终极缓存 (0ms)', needReload: true, hint: '需刷新' }, { cat: '缓存与网络', key: 'opt_block_offline', label: '屏蔽掉线弹窗', needReload: true, hint: '需刷新' } ]; // 贴边把手箭头(指向页面内侧,展开时由 CSS 旋转 90° 指向下方) const TAB_ICON = ''; const CONSOLE_CSS = ` :root { --myoa-dock-y: 25px; } /* 贴边竖向把手:始终贴边、可点击,不做滑出/展开形变 */ #myoa-fab { position: fixed; bottom: var(--myoa-dock-y); z-index: 2147483646; box-sizing: border-box; width: 22px; height: 54px; background: linear-gradient(180deg, #5aa8ff, #1677ff); color: #fff; border: 1px solid rgba(255,255,255,.85); display: flex; align-items: center; justify-content: center; cursor: pointer; user-select: none; touch-action: none; box-shadow: 0 4px 12px rgba(22,119,255,.4); transition: transform .28s cubic-bezier(.34,1.4,.64,1), opacity .28s ease, box-shadow .28s ease; } #myoa-fab.side-left { left: 0; border-radius: 0 12px 12px 0; } #myoa-fab.side-right { right: 0; border-radius: 12px 0 0 12px; } #myoa-fab:hover { transform: scale(1.08); } #myoa-fab.open { box-shadow: 0 4px 14px rgba(22,119,255,.65); } #myoa-fab.dragging { transition: none; cursor: grabbing; } #myoa-fab .ico { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; } #myoa-fab svg { width: 18px; height: 18px; fill: currentColor; pointer-events: none; } /* 箭头始终指向页面内侧(左=→,右=←),作为菜单入口提示 */ #myoa-fab.side-right .ico-tab svg { transform: rotate(180deg); } #myoa-fab .badge { position: absolute; top: -5px; right: -6px; min-width: 18px; height: 18px; padding: 0 4px; box-sizing: border-box; border-radius: 9px; background: #ff2442; color: #fff; font: 600 11px/18px -apple-system,sans-serif; text-align: center; box-shadow: 0 1px 4px rgba(0,0,0,.25); } #myoa-panel { position: fixed; z-index: 2147483646; width: 248px; box-sizing: border-box; max-height: calc(100vh - 24px); overflow-y: auto; background: rgba(255,255,255,.98); backdrop-filter: blur(12px); border: 1px solid rgba(0,0,0,.08); border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,.25); padding: 12px; font: 13px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif; color: #333; opacity: 0; visibility: hidden; transform: translateY(8px) scale(.96); transition: opacity .2s, transform .2s, visibility .2s; } #myoa-panel.open { opacity: 1; visibility: visible; transform: translateY(0) scale(1); } #myoa-panel.side-left { left: 60px; } #myoa-panel.side-right { right: 60px; } #myoa-panel .stat { font-size: 12px; color: #666; background: #f5f8ff; border-radius: 8px; padding: 6px 8px; margin-bottom: 8px; font-variant-numeric: tabular-nums; } #myoa-panel .row { display: flex; align-items: center; justify-content: space-between; padding: 7px 2px; border-bottom: 1px solid #f0f0f0; } #myoa-panel .row:last-of-type { border-bottom: none; } #myoa-panel .row .name { flex: 1; } #myoa-panel .row .hint { font-size: 10px; color: #c98a2e; margin-left: 6px; } #myoa-panel .sw { position: relative; width: 38px; height: 22px; border-radius: 11px; background: #d9d9d9; cursor: pointer; transition: background .2s; flex: none; } #myoa-panel .sw.on { background: #1677ff; } #myoa-panel .sw::after { content: ""; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; transition: left .2s; } #myoa-panel .sw.on::after { left: 18px; } #myoa-panel .acts { display: flex; gap: 6px; margin-top: 10px; } #myoa-panel .acts button { flex: 1; font: 11px/1 inherit; padding: 6px 0; border: 1px solid #eee; border-radius: 6px; background: #fafafa; color: #666; cursor: pointer; } #myoa-panel .acts button:hover { border-color: #1677ff; color: #1677ff; background: #f0f6ff; } /* 一级分类标题 */ #myoa-panel .cat { font-size: 11px; color: #1677ff; font-weight: 600; margin: 8px 2px 2px; padding-top: 6px; border-top: 1px dashed #e6e6e6; } #myoa-panel .cat:first-of-type { border-top: none; } /* 登录页迷你账户切换器 */ #myoa-switcher { position: fixed; left: 60px; bottom: 90px; z-index: 2147483646; width: 220px; box-sizing: border-box; background: rgba(255,255,255,.98); backdrop-filter: blur(12px); border: 1px solid rgba(0,0,0,.08); border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,.25); padding: 10px; font: 13px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif; color: #333; } #myoa-switcher .hd { font-weight: 600; display: flex; justify-content: space-between; align-items: baseline; } #myoa-switcher .hd .host { font-size: 10px; color: #888; font-weight: 400; } #myoa-switcher .cnt { font-size: 11px; color: #c98a2e; margin: 2px 0 6px; } #myoa-switcher .acc { padding: 7px 8px; border-radius: 6px; background: #f6f8fb; margin: 4px 0; cursor: pointer; } #myoa-switcher .acc:hover { background: #e9f1ff; } #myoa-switcher .acc.def { background: #e6f7e6; border: 1px solid #b7eb8f; } #myoa-switcher .acc em { color: #389e0d; font-style: normal; font-size: 11px; } #myoa-switcher .acts { display: flex; gap: 6px; margin-top: 8px; } #myoa-switcher .acts button { flex: 1; font: 11px/1 inherit; padding: 6px 0; border: 1px solid #eee; border-radius: 6px; background: #fafafa; color: #666; cursor: pointer; } #myoa-switcher .acts button:hover { border-color: #1677ff; color: #1677ff; } `; function applyUiPerf(on) { const docs = [document]; // 收集主文档与同域业务 iframe(zwIframe / 弹层 iframe),跨域则跳过 document.querySelectorAll('iframe').forEach(f => { if (f.id === 'zwIframe' || f.id.startsWith('layui-layer-iframe')) { try { if (f.contentDocument) docs.push(f.contentDocument); } catch (e) {} } }); docs.forEach(d => { const tag = d.getElementById('myoa-opt-style'); if (on) { if (!tag) injectStyles(d); } // 注入(已存在则跳过) else if (tag) { tag.remove(); } // 即时回收样式 }); } let _statDb = null; // ponytail: 复用单一 IDB 连接,避免每 3s 重开连接累积 function updateCacheStat() { const fab = document.getElementById('myoa-fab'), badge = fab && fab.querySelector('.badge'); const stat = document.getElementById('myoa-stat'); if (!getSetting('opt_web_cache')) { if (badge) badge.style.display = 'none'; if (stat) stat.textContent = '网页缓存已关闭'; return; } const savedMB = (cacheSavedBytes / 1048576).toFixed(1); if (badge) { badge.style.display = 'block'; badge.textContent = cacheHits > 99 ? '99+' : cacheHits; } const setText = (txt) => { const st = document.getElementById('myoa-stat'); if (st) st.textContent = txt; }; const countCache = () => { try { const tx = _statDb.transaction('cache', 'readonly'); tx.objectStore('cache').count().onsuccess = (ev) => setText(`已缓存 ${ev.target.result} 文件 · 本次命中 ${cacheHits} 次 · 节省 ${savedMB} MB`); tx.onerror = () => setText(`本次命中 ${cacheHits} 次 · 节省 ${savedMB} MB`); } catch (e) { setText(`本次命中 ${cacheHits} 次 · 节省 ${savedMB} MB`); } }; if (!_statDb) { try { const r = _win.indexedDB.open('UltimateWebCache_v3', 1); r.onsuccess = (e) => { _statDb = e.target.result; countCache(); }; r.onerror = () => setText(`本次命中 ${cacheHits} 次 · 节省 ${savedMB} MB`); } catch (e) { setText(`本次命中 ${cacheHits} 次 · 节省 ${savedMB} MB`); } return; } countCache(); } const DOCK_KEY = 'myoa_dock'; function buildConsole() { if (!isTopFrame || document.getElementById('myoa-fab')) return; const style = document.createElement('style'); style.id = 'myoa-console-style'; style.textContent = CONSOLE_CSS; (document.head || document.documentElement).appendChild(style); const saved = (() => { try { return JSON.parse(localStorage.getItem(DOCK_KEY)) || {}; } catch (e) { return {}; } })(); const dock = { side: saved.side === 'right' ? 'right' : 'left', y: typeof saved.y === 'number' ? saved.y : 25 }; const root = document.documentElement; let drag = null, suppressClick = false; const fab = document.createElement('div'); fab.id = 'myoa-fab'; fab.title = 'OA 优化控制台(点击展开 · 可拖动吸附)'; fab.innerHTML = `${TAB_ICON}`; document.body.appendChild(fab); const panel = document.createElement('div'); panel.id = 'myoa-panel'; panel.innerHTML = '
读取缓存统计中…
'; let lastCat = null; SETTINGS_META.forEach(m => { if (m.cat && m.cat !== lastCat) { lastCat = m.cat; const cat = document.createElement('div'); cat.className = 'cat'; cat.textContent = lastCat; panel.appendChild(cat); } const row = document.createElement('div'); row.className = 'row'; const on = getSetting(m.key); row.innerHTML = `${m.label}${m.hint ? `${m.hint}` : ''}`; row.querySelector('.sw').addEventListener('click', () => toggleSetting(m, row)); panel.appendChild(row); }); const acts = document.createElement('div'); acts.className = 'acts'; acts.innerHTML = ''; panel.appendChild(acts); document.body.appendChild(panel); const isOpen = () => panel.classList.contains('open'); const setDock = (side, y) => { dock.side = side === 'right' ? 'right' : 'left'; dock.y = Math.max(8, Math.min(y, _win.innerHeight - 60)); root.style.setProperty('--myoa-dock-y', dock.y + 'px'); fab.classList.toggle('side-left', dock.side === 'left'); fab.classList.toggle('side-right', dock.side === 'right'); panel.classList.toggle('side-left', dock.side === 'left'); panel.classList.toggle('side-right', dock.side === 'right'); try { localStorage.setItem(DOCK_KEY, JSON.stringify(dock)); } catch (e) {} }; // 面板垂直居中对齐 FAB,并限制在视口内 const placePanel = () => { const r = fab.getBoundingClientRect(), h = panel.offsetHeight || 320; panel.style.top = Math.max(8, Math.min(r.top + r.height / 2 - h / 2, _win.innerHeight - h - 8)) + 'px'; }; setDock(dock.side, dock.y); // 始终贴边,不做滑出/收起 _win.addEventListener('resize', () => { setDock(dock.side, dock.y); if (isOpen()) placePanel(); }); // 拖动:跟随鼠标自由移动,松手后吸附到最近一侧边缘 fab.addEventListener('mousedown', (e) => { if (e.button !== 0) return; e.preventDefault(); suppressClick = false; const r = fab.getBoundingClientRect(); drag = { sx: e.clientX, sy: e.clientY, ox: r.left, oy: r.top, moved: false }; }); document.addEventListener('mousemove', (e) => { if (!drag) return; const dx = e.clientX - drag.sx, dy = e.clientY - drag.sy; if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 5) return; if (!drag.moved) { drag.moved = true; if (isOpen()) panel.classList.remove('open'); } fab.classList.add('dragging'); fab.style.transform = 'none'; fab.style.left = Math.max(-8, Math.min(drag.ox + dx, _win.innerWidth - 40)) + 'px'; fab.style.right = 'auto'; fab.style.top = Math.max(-8, Math.min(drag.oy + dy, _win.innerHeight - 40)) + 'px'; fab.style.bottom = 'auto'; }, { passive: true }); document.addEventListener('mouseup', (e) => { if (!drag) return; const moved = drag.moved; drag = null; fab.classList.remove('dragging'); fab.style.left = fab.style.right = fab.style.top = fab.style.bottom = fab.style.transform = ''; if (!moved) return; suppressClick = true; setDock(e.clientX < _win.innerWidth / 2 ? 'left' : 'right', _win.innerHeight - (fab.getBoundingClientRect().top + 27)); }); fab.addEventListener('click', (e) => { if (suppressClick) { suppressClick = false; return; } e.stopPropagation(); panel.classList.toggle('open'); fab.classList.toggle('open', isOpen()); if (isOpen()) { placePanel(); updateCacheStat(); } }); document.addEventListener('click', (e) => { if (isOpen() && !panel.contains(e.target) && !fab.contains(e.target)) { panel.classList.remove('open'); fab.classList.remove('open'); } }); document.getElementById('myoa-am').addEventListener('click', () => openAccountManager()); document.getElementById('myoa-clear-cache').addEventListener('click', () => { if (_win.indexedDB) _win.indexedDB.deleteDatabase('UltimateWebCache_v3'); _statDb = null; // 连接已随库销毁,下次重新打开 localStorage.removeItem('uwc_tracker'); cacheHits = 0; cacheSavedBytes = 0; updateCacheStat(); alert('缓存已清空!'); }); } function toggleSetting(m, row) { const next = !getSetting(m.key); setSetting(m.key, next); row.querySelector('.sw').classList.toggle('on', next); if (m.key === 'opt_ui_perf') applyUiPerf(next); else if (m.needReload && confirm(`「${m.label}」需刷新页面才能生效,是否立即刷新?`)) { _win.location.reload(); } } (function mountConsole() { const ready = () => { if (!isTopFrame) return; buildConsole(); updateCacheStat(); setInterval(updateCacheStat, 3000); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready, { once: true }); else ready(); })(); })();