diff --git a/extension/manifest.json b/extension/manifest.json index d0b3a65..1439ba3 100644 --- a/extension/manifest.json +++ b/extension/manifest.json @@ -14,6 +14,11 @@ "permissions": ["storage"], + "host_permissions": [ + "http://localhost:17300/*", + "http://127.0.0.1:17300/*" + ], + "action": { "default_title": "云仓视频溯源", "default_popup": "src/popup.html", diff --git a/extension/src/background.js b/extension/src/background.js index 70ee64f..2a0c9d6 100644 --- a/extension/src/background.js +++ b/extension/src/background.js @@ -13,7 +13,15 @@ */ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { - if (!msg || msg.type !== 'pst:open') return; + if (!msg) return; + + // 探测本机软件是否在跑(协议唤起到底成没成,靠它判断) + if (msg.type === 'pst:probe') { + probeLocalService().then(sendResponse, () => sendResponse({ online: false })); + return true; + } + + if (msg.type !== 'pst:open') return; openTarget(msg, sender).then(sendResponse, err => { sendResponse({ ok: false, message: String((err && err.message) || err) }); @@ -21,6 +29,29 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { return true; // 异步响应 }); +/** + * 探测本机软件是否在跑。 + * + * 为什么不去看「页面有没有失焦」:软件已经在跑时,协议只是把参数转给已有实例, + * 窗口可能不抢焦点;冷启动也可能超过几秒 —— 两种都会误报「没打开」。 + * 但软件只要在跑就一定监听 17300,**任何 HTTP 响应(200/400/401)都算成功**。 + */ +async function probeLocalService(timeoutMs = 1500) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + const res = await fetch('http://localhost:17300/api/query/', { + cache: 'no-store', + signal: controller.signal, + }); + return { online: true, status: res.status }; + } catch (_) { + return { online: false }; + } finally { + clearTimeout(timer); + } +} + async function openTarget(msg, sender) { const url = String(msg.url || '').trim(); if (!/^https?:\/\//i.test(url)) { diff --git a/extension/src/content.css b/extension/src/content.css index d24cadc..329fcca 100644 --- a/extension/src/content.css +++ b/extension/src/content.css @@ -10,6 +10,48 @@ * 都不参与布局,所以标记前后页面不会跳;chip 会撑开一点,用负 margin 抵掉。 */ +/* ============ 默认方式:在命中元素旁边渲染的「查看打包视频」按钮 ============ + * 这个按钮是**新增的兄弟节点**,宿主元素一个字都没改,所以不会影响页面原有的事件。 + * 又因为它被放在别人的表格/列表里,得抵抗 Element-Plus 这类全局 button 样式,所以属性写得比较霸道。 + */ +.pst-trace-btn { + display: inline-block !important; + margin: 0 0 0 6px !important; + padding: 1px 7px !important; + border: 0 !important; + border-radius: 3px !important; + background: #0ea5a4 !important; + color: #fff !important; + font-family: inherit !important; + font-size: 11px !important; + line-height: 16px !important; + font-weight: 400 !important; + letter-spacing: 0 !important; + text-transform: none !important; + text-align: center !important; + vertical-align: middle !important; + white-space: nowrap !important; + width: auto !important; + min-width: 0 !important; + height: auto !important; + min-height: 0 !important; + box-shadow: none !important; + outline: 0 !important; + -webkit-user-select: none; + user-select: none; +} +.pst-trace-btn::before { + content: '\25B6'; /* ▶ */ + font-size: 8px !important; + margin-right: 4px; + vertical-align: 1px; +} +.pst-trace-btn:hover { background: #0b8c8b !important; } +.pst-trace-btn:active { background: #0b7d7c !important; } + +/* text 模式下给按钮定位用的 span:不带任何视觉,只是想有个锚点 */ +.pst-trace-anchor { display: inline !important; } + .pst-trace-mark { cursor: pointer !important; border-radius: 3px; diff --git a/extension/src/content.js b/extension/src/content.js index 05575db..3353722 100644 --- a/extension/src/content.js +++ b/extension/src/content.js @@ -134,8 +134,12 @@ maxNodes: state.config.maxNodes, maxMarks: state.config.maxMarks, defaultStyle: state.config.markStyle, + defaultActionMode: state.config.actionMode, + buttonText: state.config.buttonText, showIcon: state.config.showIcon, urlTemplate: state.config.urlTemplate, + appUrlTemplate: state.config.appUrlTemplate, + openMode: state.config.openMode, hostname: location.hostname, host: location.host, }); @@ -198,7 +202,159 @@ el.classList.add('pst-open'); setTimeout(() => el.classList.remove('pst-open'), 700); - sendToBackground({ type: 'pst:open', url, code, mode: state.config.openMode }); + openTargetUrl(url, code); + } + + /** + * 按 url 协议分流: + * - http/https → 交给 background(chrome.tabs/windows,不受宿主页弹窗拦截器影响) + * - 其它(`yuncang://` 等自定义协议)→ 必须在**本页、用户手势里**触发, + * 且浏览器不会回任何结果 → 起超时兜底 + */ + function openTargetUrl(url, code) { + if (/^https?:\/\//i.test(url)) { + sendToBackground({ type: 'pst:open', url, code, mode: state.config.openMode }); + return; + } + launchProtocol(url, code); + } + + /** 当前弹出的兜底卡片(同一时刻只留一个) */ + let fallbackEl = null; + + /** + * 用自定义协议唤起本机软件(`yuncang://open?code=xxx`) + * + * 为什么需要兜底: + * 没安装 / 协议没注册 / 用户在 Chrome 的「要打开吗」上点了取消 —— 三种情况网页侧**完全一样**(静默)。 + * 所以:4 秒内页面没失焦(软件窗口没抢焦点),就当没起来,弹「在网页中查看 / 下载安装」。 + */ + function launchProtocol(url, code) { + const frame = document.createElement('iframe'); + frame.style.cssText = 'position:fixed;width:0;height:0;border:0;opacity:0;pointer-events:none;'; + frame.src = url; + (document.body || document.documentElement).appendChild(frame); + + let settled = false; + const maxWait = 8000; // 冷启动(自解压 + 恢复登录)留足时间 + const step = 700; + const started = Date.now(); + + const onLeave = () => { + // 软件窗口/浏览器确认框把焦点抢走 → 认为已唤起 + if (document.visibilityState === 'hidden' || !document.hasFocus()) finish(true); + }; + + window.addEventListener('blur', onLeave); + document.addEventListener('visibilitychange', onLeave); + + // 更可靠的判据:本机服务是否有响应(软件在跑就一定监听 17300)。 + // 仅看「页面失焦」会误报:软件本来就在跑时只是转发参数,窗口不一定抢焦点。 + const timer = setInterval(async () => { + if (settled) return; + + const online = await probeLocalService(); + if (settled) return; + + if (online) { finish(true); return; } + if (Date.now() - started >= maxWait) finish(false); + }, step); + + function finish(ok) { + if (settled) return; + settled = true; + clearInterval(timer); + window.removeEventListener('blur', onLeave); + document.removeEventListener('visibilitychange', onLeave); + setTimeout(() => frame.remove(), 200); + + if (!ok) { + log('协议唤起无响应(探测不到本机服务),弹出兜底提示:' + url); + showFallback(code); + } + } + } + + /** 问 background 本机服务在不在(扩展带 host 权限,不受页面 CSP 影响) */ + function probeLocalService() { + return new Promise(resolve => { + try { + chrome.runtime.sendMessage({ type: 'pst:probe' }, res => { + void chrome.runtime.lastError; + resolve(!!(res && res.online)); + }); + } catch (_) { + resolve(false); + } + }); + } + + /** 兜底卡片:网页中查看(页面里有下载入口)+ 可选下载安装 */ + function showFallback(code) { + if (fallbackEl) { fallbackEl.remove(); fallbackEl = null; } + + const cfg = state.config; + const wrap = document.createElement('div'); + wrap.setAttribute('data-pst-fallback', '1'); + Object.assign(wrap.style, { + position: 'fixed', right: '20px', bottom: '20px', zIndex: '2147483647', + maxWidth: '330px', padding: '14px 16px', borderRadius: '12px', + background: '#fff', color: '#1f2430', border: '1px solid #e5e7eb', + boxShadow: '0 8px 28px rgba(0,0,0,.16)', + font: '13px/1.6 "Microsoft YaHei UI", system-ui, sans-serif', + textAlign: 'left', + }); + + const title = document.createElement('div'); + title.textContent = '没打开本机软件?'; + Object.assign(title.style, { fontWeight: '600', marginBottom: '6px' }); + wrap.appendChild(title); + + const desc = document.createElement('div'); + desc.textContent = '可能还没安装,或者浏览器拦了这次打开请求。'; + Object.assign(desc.style, { color: '#6b7280', marginBottom: '10px' }); + wrap.appendChild(desc); + + const row = document.createElement('div'); + Object.assign(row.style, { display: 'flex', gap: '8px', flexWrap: 'wrap' }); + + const webUrl = R.buildUrl(cfg.fallbackUrl, code, location.host); + row.appendChild(fallbackButton('在网页中查看', true, () => { + sendToBackground({ type: 'pst:open', url: webUrl, code, mode: 'tab' }); + close(); + })); + + if (cfg.downloadUrl) { + row.appendChild(fallbackButton('下载安装', true, () => { + sendToBackground({ type: 'pst:open', url: cfg.downloadUrl, code, mode: 'tab' }); + close(); + })); + } + + row.appendChild(fallbackButton('关闭', false, close)); + wrap.appendChild(row); + document.documentElement.appendChild(wrap); + fallbackEl = wrap; + + function close() { + wrap.remove(); + if (fallbackEl === wrap) fallbackEl = null; + } + } + + function fallbackButton(text, primary, onClick) { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.textContent = text; + Object.assign(btn.style, { + padding: '6px 12px', borderRadius: '7px', cursor: 'pointer', + fontSize: '13px', lineHeight: '1.4', + border: primary ? '0' : '1px solid #e5e7eb', + background: primary ? '#2563eb' : 'transparent', + color: primary ? '#fff' : '#6b7280', + }); + btn.addEventListener('click', onClick, true); + return btn; } /* -------------------------------------------------------- 消息 / 配置 */ @@ -219,7 +375,7 @@ } if (msg.type === 'pst:open') { // popup 列表里点某一条 - sendToBackground({ type: 'pst:open', url: msg.url, code: msg.code, mode: state.config.openMode }); + openTargetUrl(msg.url, msg.code); sendResponse({ ok: true }); return; } @@ -235,6 +391,8 @@ host: location.host, hosts: state.config.hosts, openMode: state.config.openMode, + actionMode: state.config.actionMode, + buttonText: state.config.buttonText, urlTemplate: state.config.urlTemplate, ruleCount: state.compiled.rules.length, ruleErrors: state.ruleErrors, @@ -263,7 +421,7 @@ out.push({ ruleId, code, - text: (el.textContent || '').trim(), + text: code, url: el.getAttribute('data-pst-url') || '', }); if (out.length >= 50) break; diff --git a/extension/src/lib/rules.js b/extension/src/lib/rules.js index 4aa6eac..cace13c 100644 --- a/extension/src/lib/rules.js +++ b/extension/src/lib/rules.js @@ -14,8 +14,24 @@ */ (function (root) { const STORAGE_KEY = 'pstConfig'; - const DEFAULT_URL_TEMPLATE = 'https://www.baidu.com/?keyword={code}'; + // 网页模板(openMode = window / tab 时用):打开本机软件的公共页 + const DEFAULT_URL_TEMPLATE = 'http://localhost:7301/local?code={code}'; + // 协议模板(openMode = app 时用):**直接唤起本机软件**并带上单号 + // ⚠️ 自定义协议拿不到任何结果(成功/没装/用户点取消在网页侧一模一样), + // 所以 content script 必须配合超时兜底(弹「下载安装 / 在网页中查看」)。 + const DEFAULT_APP_URL_TEMPLATE = 'yuncang://open?code={code}'; + /** 兜底页:协议唤不起时「去网页看看」(页面里会提示下载安装、并能在浏览器里直接查) */ + const DEFAULT_FALLBACK_URL = 'http://localhost:7301/local?code={code}'; + /** 点击后的打开方式:app = 协议唤起本机软件;window = 独立小窗;tab = 新标签页 */ + const OPEN_MODES = ['app', 'window', 'tab']; + const DEFAULT_BUTTON_TEXT = '查看打包视频'; const MARK_STYLES = ['underline', 'highlight', 'chip']; + /** + * 加工方式: + * button(默认)—— 完全不动命中元素,只在它旁边插一个按钮; + * chip —— 命中元素本身可点(加类名 / 改 title / 接管点击)。 + */ + const ACTION_MODES = ['button', 'chip']; /** 这些元素的文本不参与匹配(避免破坏表单/脚本/媒体) */ const SKIP_TAGS = new Set([ @@ -25,69 +41,44 @@ ]); /** - * 内置示例规则。 - * 注意:默认规则要「宁可漏、不可错」——太宽的正则(比如纯 12~20 位数字) - * 会把时间戳、内部 ID 全部点亮,页面上到处是下划线,反而没人敢用。 + * 单号前缀表(**要维护就改这一行**):新出现的快递公司前缀直接往数组里加就行, + * 只要是以前没出现过、又确实出现在单号开头的,加进来即可 —— 通用文本规则就靠它认单号。 + * ⚠️ 数字前缀(如 32 / 77)最容易把内部 ID、订单号一起点亮,发现误标再回来调整。 + */ + const EXPRESS_PREFIXES = [ 'YT', 'SF', 'JD', 'ZTO', 'YTO', 'STO', 'EMS', 'DBL', '32', '77' ]; + + /** 通用运单号文本规则:前缀 + 10~16 位数字 */ + const EXPRESS_PATTERN = '\\b(?:' + EXPRESS_PREFIXES.join('|') + ')\\d{10,16}\\b'; + + /** 上一版 express 的正则:只有用户没改过它时,才在升级时跟着换新 */ + const LEGACY_EXPRESS_PATTERN = '\\b(?:YT|SF|JD|ZTO|YTO|STO|EMS|DBL)\\d{10,16}\\b'; + + /** 已经移除的示例规则 id(老配置升级时从用户的规则里剔掉) */ + const REMOVED_RULE_IDS = [ 'wms-waybill', 'numeric', 'legacy-postnum', 'dom-attr' ]; + + /** 配置版本:升版本号 = 下次打开页面时跑一次 upgradeRules() */ + const CONFIG_VERSION = 4; + + /** + * 内置规则:**只留这一条通用文本规则**。 + * (2026-10-17 起把 WMS 选择器 / 纯数字 / legacy postNum / data-attr 这四条示例规则都删了 —— + * 实测「前缀 + 10~16 位数字」已经盖住真实页面的运单号,不够用再加前缀即可。) + * + * 前缀表见 EXPRESS_PREFIXES:新前缀往那里加,不用改正则本身。 */ const DEFAULT_RULES = [ - { - // ★ 取样自 https://wms.wms.gztbyc.com/order/orderManagement - // 行内 HTML:321408064481776 - // 同一行里还有「点击复制发货单号」「点击复制波次号」「点击复制平台交易单号」几个同类 span, - // 所以用 title 里的「快递单号」做区分,只认真正的运单号。 - id: 'wms-waybill', - name: '运单号(WMS 快递单号字段 · 取样自 gztbyc WMS)', - enabled: true, - match: 'selector', - selector: '[title*="快递单号"]', - attr: '', // 空 = 取元素文本 - pattern: '', - flags: '', - exclude: '', - hostPatterns: ['wms.wms.gztbyc.com', '*.gztbyc.com'], - style: 'underline', - urlTemplate: '', - }, { id: 'express', - name: '快递单号(YT / SF / JD / ZTO / YTO / STO / EMS… 通用文本规则)', + name: '快递单号(YT / SF / JD / ZTO / YTO / STO / EMS / 32 / 77… 通用文本规则)', enabled: true, match: 'text', - pattern: '\\b(?:YT|SF|JD|ZTO|YTO|STO|EMS|DBL)\\d{10,16}\\b', + pattern: EXPRESS_PATTERN, flags: 'gi', exclude: '', selector: '', attr: '', hostPatterns: ['*'], - style: '', - urlTemplate: '', - }, - { - id: 'numeric', - name: '纯数字单号(12~20 位,示例,默认关闭)', - enabled: false, - match: 'text', - pattern: '\\b\\d{12,20}\\b', - flags: 'g', - // 13 位数字常是毫秒时间戳,10 位常是秒级时间戳;13 位运单号也不少见 —— 开之前先想清楚 - exclude: '\\b1[0-9]{9}(?:[0-9]{3})?\\b', - selector: '', - attr: '', - hostPatterns: ['*'], - style: '', - urlTemplate: '', - }, - { - id: 'dom-attr', - name: '按 DOM 属性取号(示例,默认关闭)', - enabled: false, - match: 'selector', - pattern: '', - flags: '', - exclude: '', - selector: '[data-order-no]', - attr: 'data-order-no', - hostPatterns: ['*'], + actionMode: '', // 空 = 跟随全局(默认 button:旁边插按钮,不碰宿主元素) style: '', urlTemplate: '', }, @@ -97,11 +88,16 @@ function defaultConfig() { return JSON.parse(JSON.stringify({ - version: 1, + version: CONFIG_VERSION, enabled: true, hosts: ['*'], urlTemplate: DEFAULT_URL_TEMPLATE, - openMode: 'window', // window = 独立小窗(默认);tab = 新标签页 + appUrlTemplate: DEFAULT_APP_URL_TEMPLATE, + fallbackUrl: DEFAULT_FALLBACK_URL, + downloadUrl: '', // 软件安装包/下载页;空 = 兜底卡片只给「去网页查看」 + openMode: 'app', // app = 直接唤起本机软件(默认);window = 独立小窗;tab = 新标签页 + actionMode: 'button', // button = 旁边插按钮(默认,不碰宿主元素);chip = 元素本身可点 + buttonText: DEFAULT_BUTTON_TEXT, markStyle: 'underline', showIcon: true, scanDelay: 400, // DOM 变动后延迟多久重扫(毫秒) @@ -116,11 +112,23 @@ const src = raw && typeof raw === 'object' ? raw : {}; const cfg = Object.assign(dft, src); - cfg.version = 1; + cfg.version = CONFIG_VERSION; cfg.enabled = cfg.enabled !== false; cfg.hosts = toStrArray(cfg.hosts, ['*']); cfg.urlTemplate = String(cfg.urlTemplate || '').trim() || DEFAULT_URL_TEMPLATE; - cfg.openMode = cfg.openMode === 'window' ? 'window' : 'tab'; + cfg.appUrlTemplate = String(cfg.appUrlTemplate || '').trim() || DEFAULT_APP_URL_TEMPLATE; + cfg.fallbackUrl = String(cfg.fallbackUrl || '').trim() || DEFAULT_FALLBACK_URL; + cfg.downloadUrl = String(cfg.downloadUrl || '').trim(); + cfg.openMode = OPEN_MODES.indexOf(cfg.openMode) >= 0 ? cfg.openMode : 'app'; + + // v3 把「协议模板」当成了 urlTemplate 的默认值(当时没有 openMode=app 这个概念); + // 升到 v4:模板还原成网页模板,改用 openMode='app' 表达「直接唤起」,行为不变。 + if (Number(src.version || 1) < 4 && String(src.urlTemplate || '').trim() === DEFAULT_APP_URL_TEMPLATE) { + cfg.urlTemplate = DEFAULT_URL_TEMPLATE; + cfg.openMode = 'app'; + } + cfg.actionMode = ACTION_MODES.indexOf(cfg.actionMode) >= 0 ? cfg.actionMode : 'button'; + cfg.buttonText = String(cfg.buttonText == null ? '' : cfg.buttonText).trim() || DEFAULT_BUTTON_TEXT; cfg.markStyle = MARK_STYLES.indexOf(cfg.markStyle) >= 0 ? cfg.markStyle : 'underline'; cfg.showIcon = cfg.showIcon !== false; cfg.scanDelay = clampInt(cfg.scanDelay, 0, 5000, 400); @@ -132,10 +140,33 @@ cfg.rules = dft.rules; } else { cfg.rules = src.rules.map(normalizeRule).filter(Boolean); + // 老版本的配置(version < CONFIG_VERSION)跟着扩展升级一次:删掉已移除的示例规则、刷新内置规则的前缀表 + if (Number(src.version || 1) < CONFIG_VERSION) cfg.rules = upgradeRules(cfg.rules); } return cfg; } + /** + * 配置升级(只在 version 变高时跑一次): + * 1. 剔掉已经移除的内置示例规则(REMOVED_RULE_IDS); + * 2. 内置的 express 若还是老正则(用户没自己改过),就换成带新前缀表的正则。 + * 用户自己加的规则一律不动。 + */ + function upgradeRules(rules) { + return rules + .filter(rule => REMOVED_RULE_IDS.indexOf(rule.id) < 0) + .map(rule => { + if (rule.id !== 'express') return rule; + if (String(rule.pattern).trim() !== LEGACY_EXPRESS_PATTERN) return rule; // 用户改过就尊重他的 + return Object.assign({}, rule, { + name: DEFAULT_RULES[0].name, + match: 'text', + pattern: EXPRESS_PATTERN, + flags: 'gi', + }); + }); + } + function normalizeRule(raw) { if (!raw || typeof raw !== 'object') return null; return { @@ -149,6 +180,7 @@ selector: String(raw.selector == null ? '' : raw.selector), attr: String(raw.attr == null ? '' : raw.attr).trim(), hostPatterns: toStrArray(raw.hostPatterns, ['*']), + actionMode: ACTION_MODES.indexOf(raw.actionMode) >= 0 ? raw.actionMode : '', // 空 = 跟随全局 style: MARK_STYLES.indexOf(raw.style) >= 0 ? raw.style : '', urlTemplate: String(raw.urlTemplate == null ? '' : raw.urlTemplate).trim(), }; @@ -168,6 +200,11 @@ for (const rule of Array.isArray(rules) ? rules : []) { if (!rule || rule.enabled === false) continue; try { + const ptn = String(rule.pattern || '').trim(); + const ex = String(rule.exclude || '').trim(); + const excludeRe = ex ? new RegExp(ex, 'g') : null; + let re = null; + if (rule.match === 'selector') { const sel = String(rule.selector || '').trim(); if (!sel) throw new Error('CSS 选择器不能为空'); @@ -175,14 +212,16 @@ // 仅做语法校验:非法选择器会让 querySelector 直接抛异常 document.createDocumentFragment().querySelector(sel); } - list.push({ rule, re: null, excludeRe: null }); + // 选择器模式下正则是**可选**的:填了就用来从取到的属性值/文本里再抽一次编号。 + // 典型场景: + // —— 编号藏在 href 里,整条属性值不能当编号,必须再抽一层。 + if (ptn) re = new RegExp(ptn, normalizeFlags(rule.flags)); } else { - const ptn = String(rule.pattern || '').trim(); if (!ptn) throw new Error('正则表达式不能为空'); - const re = new RegExp(ptn, normalizeFlags(rule.flags)); - const ex = String(rule.exclude || '').trim(); - list.push({ rule, re, excludeRe: ex ? new RegExp(ex, 'g') : null }); + re = new RegExp(ptn, normalizeFlags(rule.flags)); } + + list.push({ rule, re, excludeRe }); } catch (e) { errors.push({ id: rule.id, name: rule.name, message: shortMessage(e) }); } @@ -258,19 +297,24 @@ if (p.namespaceURI && p.namespaceURI !== 'http://www.w3.org/1999/xhtml') return false; if (SKIP_TAGS.has(p.tagName)) return false; if (p.isContentEditable) return false; - // 已经标过的(含我们自己的 span、以及 selector 模式标过的宿主元素)不再重复处理 - if (p.closest && p.closest('.' + markClass + ', [data-pst-skip]')) return false; + // 已经加工过的(chip 标记 / text 模式的定位 span / 按钮)都不再处理: + // 一律看 data-pst-code —— button 模式不会给宿主元素加类名,只看类名会漏。 + if (p.closest && p.closest('.' + markClass + ', [data-pst-code], [data-pst-skip]')) return false; return true; } /* ---------------------------------------------------------- DOM 标记 */ /** - * 扫描 rootEl 并按规则「二次加工」: - * - text 规则:把命中的子串包成 (原文本完整保留在 span 里, - * 所以页面自己读 textContent / 复制粘贴拿到的内容都不变) - * - selector 规则:直接给命中的元素打标(加类名 + data-pst-* 属性) - * 两种方式都会带上 data-pst-code / data-pst-url,点击拦截统一按类名认。 + * 扫描 rootEl 并按规则「二次加工」,= 两种匹配 × 两种加工方式: + * + * 匹配:text 规则(遍历文本节点按正则找) / selector 规则(CSS 选择器命中元素) + * 加工:button(默认)= **完全不碰命中元素**,只在它旁边插一个兄弟按钮 + * chip = 命中元素本身可点(会加类名 / 改 title / 接管点击) + * + * button 方式下宿主元素只被写两个 data-* 属性当「已处理」记号, + * 类名 / title / role / tabindex 一律不动 —— 所以元素的外观和它自己的点击行为都不受影响。 + * 自己新建的元素一律带 data-pst-code,acceptTextNode 见到就跳过,保证不会自我嵌套。 * * @param {Element|Document} rootEl * @param {{rules:Array}} compiled @@ -285,6 +329,8 @@ const markClass = o.markClass || 'pst-trace-mark'; const maxNodes = clampInt(o.maxNodes, 100, 50000, 5000); const maxMarks = clampInt(o.maxMarks, 1, 5000, 400); + const defaultAction = ACTION_MODES.indexOf(o.defaultActionMode) >= 0 ? o.defaultActionMode : 'button'; + const buttonText = String(o.buttonText == null ? '' : o.buttonText).trim() || DEFAULT_BUTTON_TEXT; const items = []; const marks = []; const seen = new Set(); @@ -293,6 +339,10 @@ if (!rootEl || !doc) return { items, marks, truncated }; function urlFor(rule, code) { + // 「直接唤起本机软件」:用协议模板(规则级的网页模板不参与) + if (o.openMode === 'app') { + return buildUrl(o.appUrlTemplate || DEFAULT_APP_URL_TEMPLATE, code, o.host); + } const tpl = rule.urlTemplate || o.urlTemplate || DEFAULT_URL_TEMPLATE; return buildUrl(tpl, code, o.host); } @@ -306,9 +356,46 @@ } } + /** 这条规则用哪种加工方式(规则自己没写就跟随全局) */ + function actionOf(rule) { + return ACTION_MODES.indexOf(rule.actionMode) >= 0 ? rule.actionMode : defaultAction; + } + + /** 「查看打包视频」按钮:自己带 markClass,所以点击处理和命中计数都跟 chip 模式走同一条路 */ + function makeButton(rule, code) { + const btn = doc.createElement('button'); + btn.type = 'button'; + btn.className = markClass + ' pst-trace-btn'; + btn.textContent = buttonText; + btn.setAttribute('data-pst-code', code); + btn.setAttribute('data-pst-rule', rule.id); + const url = urlFor(rule, code); + if (url) { + btn.setAttribute('data-pst-url', url); + btn.title = url; + } + return btn; + } + + /** 按钮插到哪儿:命中元素自己;它若在 里则退到那个 之后(