462 lines
15 KiB
JavaScript
462 lines
15 KiB
JavaScript
'use strict';
|
||
/**
|
||
* 云仓视频溯源 · 页面注入(content script)
|
||
*
|
||
* 干三件事:
|
||
* 1. 按配置里的规则扫描页面文本 / DOM,把命中的号「二次加工」成可点击元素;
|
||
* 2. 拦截点击,算出目标地址后交给 background 打开(新标签页 / 独立小窗);
|
||
* 3. 用 MutationObserver 盯着 SPA 重渲染,自动补标。
|
||
*
|
||
* 设计前提:这是别人的页面,不能弄坏它。
|
||
* - 只包一层 span,**原文照抄**,宿主页读 textContent / 复制粘贴拿到的内容不变;
|
||
* - 点击在捕获阶段拦掉并 stopImmediatePropagation,不会触发宿主页自己的点击逻辑;
|
||
* - 关掉开关或改规则时完整撤销(unmark),页面回到原样;
|
||
* - 自己的 DOM 写入会让 MutationObserver 触发 → 用 quietUntil 时间窗把自己造成的变动挡掉,
|
||
* 否则会无限重扫。
|
||
*/
|
||
(function () {
|
||
const R = globalThis.PSTRules;
|
||
if (!R) return;
|
||
|
||
// 同一帧里可能被注入两次(比如扩展重载后又被 manifest 注入一次),只认第一次
|
||
if (globalThis.__pstTraceInjected) return;
|
||
globalThis.__pstTraceInjected = true;
|
||
|
||
const MARK_CLASS = 'pst-trace-mark';
|
||
|
||
const state = {
|
||
config: R.defaultConfig(),
|
||
compiled: { rules: [], errors: [] },
|
||
active: false,
|
||
observer: null,
|
||
timer: null,
|
||
quietUntil: 0,
|
||
truncated: false,
|
||
ruleErrors: [],
|
||
};
|
||
|
||
boot();
|
||
|
||
async function boot() {
|
||
state.config = await R.loadConfig();
|
||
compile();
|
||
try {
|
||
chrome.storage.onChanged.addListener(onStorageChanged);
|
||
chrome.runtime.onMessage.addListener(onMessage);
|
||
} catch (_) { /* 扩展被重载后 chrome.* 会失效,忽略 */ }
|
||
apply();
|
||
}
|
||
|
||
function compile() {
|
||
state.compiled = R.compileRules(state.config.rules);
|
||
state.ruleErrors = state.compiled.errors;
|
||
}
|
||
|
||
/* ------------------------------------------------------------ 生命周期 */
|
||
|
||
function apply() {
|
||
const cfg = state.config;
|
||
const on = !!cfg.enabled && R.hostAllowed(location.hostname, location.host, cfg.hosts);
|
||
|
||
if (on !== state.active) {
|
||
state.active = on;
|
||
if (on) startObserver(); else stopObserver();
|
||
}
|
||
|
||
if (!on) {
|
||
if (R.unmark(document, MARK_CLASS)) log('已还原页面(开关关闭或当前站点不在生效范围)');
|
||
state.truncated = false;
|
||
return;
|
||
}
|
||
scheduleScan(0);
|
||
}
|
||
|
||
function startObserver() {
|
||
if (state.observer) return;
|
||
if (!document.body) {
|
||
document.addEventListener('DOMContentLoaded', () => startObserver(), { once: true });
|
||
return;
|
||
}
|
||
state.observer = new MutationObserver(onMutations);
|
||
state.observer.observe(document.body, {
|
||
childList: true,
|
||
subtree: true,
|
||
characterData: true,
|
||
});
|
||
}
|
||
|
||
function stopObserver() {
|
||
if (!state.observer) return;
|
||
state.observer.disconnect();
|
||
state.observer = null;
|
||
}
|
||
|
||
function onMutations(mutations) {
|
||
// 自己刚写过 DOM → 这批回调是自己的回声,忽略
|
||
if (performance.now() < state.quietUntil) return;
|
||
|
||
for (const m of mutations) {
|
||
if (m.type === 'characterData') {
|
||
if (!insideMark(m.target)) { scheduleScan(); return; }
|
||
continue;
|
||
}
|
||
if (m.addedNodes && m.addedNodes.length) {
|
||
for (const n of m.addedNodes) {
|
||
if (n.nodeType === 1 && n.classList && n.classList.contains(MARK_CLASS)) continue;
|
||
if (insideMark(n)) continue;
|
||
scheduleScan();
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
function insideMark(node) {
|
||
const el = node && (node.nodeType === 1 ? node : node.parentElement);
|
||
return !!(el && el.closest && el.closest('.' + MARK_CLASS));
|
||
}
|
||
|
||
function scheduleScan(delay) {
|
||
clearTimeout(state.timer);
|
||
const wait = delay == null ? state.config.scanDelay : delay;
|
||
state.timer = setTimeout(() => {
|
||
state.timer = null;
|
||
runScan();
|
||
}, wait);
|
||
}
|
||
|
||
function runScan() {
|
||
if (!state.active || !document.body) return;
|
||
|
||
state.quietUntil = performance.now() + 150;
|
||
const res = R.applyMarks(document.body, state.compiled, {
|
||
markClass: MARK_CLASS,
|
||
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,
|
||
});
|
||
state.quietUntil = performance.now() + 150;
|
||
|
||
// ⚠️ 这里**不能**用 res.items 当“当前页命中数”:
|
||
// applyMarks 只处理「还没标过的」节点,滚动/翻页是增量补标,res.items 只是本轮新增。
|
||
// 真正可靠的口径是直接数 DOM 上的标记(见 collectItems)。
|
||
state.truncated = res.truncated;
|
||
if (res.items.length) {
|
||
log('新增命中 ' + res.items.length + ' 处,当前页共标记 ' + markElements().length + ' 处'
|
||
+ (res.truncated ? '(已达上限,可能有遗漏)' : ''));
|
||
}
|
||
if (state.ruleErrors.length) {
|
||
for (const e of state.ruleErrors) log('规则「' + e.name + '」编译失败:' + e.message, true);
|
||
}
|
||
}
|
||
|
||
/* -------------------------------------------------------------- 交互 */
|
||
|
||
document.addEventListener('click', onClick, true);
|
||
document.addEventListener('auxclick', onClick, true); // 鼠标中键
|
||
document.addEventListener('keydown', onKeydown, true);
|
||
|
||
function onClick(e) {
|
||
const el = markFrom(e.target);
|
||
if (!el) return;
|
||
|
||
// 修饰键放行:宿主页的元素本来可能有自己的行为(比如 WMS 那个单号 span 是「点击复制二维码」)。
|
||
// 按住 Ctrl / ⌘ / Alt / Shift 点击 = 不拦,交还给页面原来的处理。
|
||
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;
|
||
|
||
// 拦死:不让宿主页的委托逻辑、也不让外层 <a> 跳走
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.stopImmediatePropagation();
|
||
openMark(el);
|
||
}
|
||
|
||
function onKeydown(e) {
|
||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||
const el = markFrom(e.target);
|
||
if (!el) return;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
openMark(el);
|
||
}
|
||
|
||
function markFrom(target) {
|
||
if (!target) return null;
|
||
const el = target.nodeType === 1 ? target : target.parentElement;
|
||
return el && el.closest ? el.closest('.' + MARK_CLASS) : null;
|
||
}
|
||
|
||
function openMark(el) {
|
||
const url = el.getAttribute('data-pst-url');
|
||
if (!url) return;
|
||
const code = el.getAttribute('data-pst-code') || '';
|
||
|
||
el.classList.add('pst-open');
|
||
setTimeout(() => el.classList.remove('pst-open'), 700);
|
||
|
||
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;
|
||
}
|
||
|
||
/* -------------------------------------------------------- 消息 / 配置 */
|
||
|
||
function onMessage(msg, sender, sendResponse) {
|
||
if (!msg) return;
|
||
|
||
if (msg.type === 'pst:status') {
|
||
sendResponse(status());
|
||
return; // 同步返回,不用 return true
|
||
}
|
||
|
||
if (msg.type === 'pst:rescan') {
|
||
if (!state.active) apply();
|
||
else { R.unmark(document, MARK_CLASS); runScan(); }
|
||
sendResponse(status());
|
||
return;
|
||
}
|
||
|
||
if (msg.type === 'pst:open') { // popup 列表里点某一条
|
||
openTargetUrl(msg.url, msg.code);
|
||
sendResponse({ ok: true });
|
||
return;
|
||
}
|
||
}
|
||
|
||
function status() {
|
||
const items = collectItems();
|
||
return {
|
||
ok: true,
|
||
active: state.active,
|
||
enabled: !!state.config.enabled,
|
||
hostAllowed: R.hostAllowed(location.hostname, location.host, state.config.hosts),
|
||
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,
|
||
truncated: state.truncated,
|
||
total: items.length,
|
||
items,
|
||
};
|
||
}
|
||
|
||
/** 页面上所有已加工过的元素(含 selector 模式标在宿主元素上的) */
|
||
function markElements() {
|
||
return Array.prototype.slice.call(document.querySelectorAll('.' + MARK_CLASS));
|
||
}
|
||
|
||
/** 从 DOM 反推命中清单:去重、限量,up 到不再关心标记是怎么产生的 */
|
||
function collectItems() {
|
||
const out = [];
|
||
const seen = new Set();
|
||
for (const el of markElements()) {
|
||
const code = el.getAttribute('data-pst-code') || '';
|
||
if (!code) continue;
|
||
const ruleId = el.getAttribute('data-pst-rule') || '';
|
||
const key = ruleId + '\u0000' + code;
|
||
if (seen.has(key)) continue;
|
||
seen.add(key);
|
||
out.push({
|
||
ruleId,
|
||
code,
|
||
text: code,
|
||
url: el.getAttribute('data-pst-url') || '',
|
||
});
|
||
if (out.length >= 50) break;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function onStorageChanged(changes, areaName) {
|
||
if (!changes || !changes[R.STORAGE_KEY]) return;
|
||
const next = R.normalizeConfig(changes[R.STORAGE_KEY].newValue);
|
||
if (JSON.stringify(next) === JSON.stringify(state.config)) return;
|
||
|
||
state.config = next;
|
||
compile();
|
||
R.unmark(document, MARK_CLASS); // 旧规则留下的标记先全部撤掉
|
||
state.truncated = false;
|
||
apply();
|
||
log('配置已更新,重新扫描');
|
||
}
|
||
|
||
/* ------------------------------------------------------------- 工具 */
|
||
|
||
function sendToBackground(msg) {
|
||
try {
|
||
chrome.runtime.sendMessage(msg, () => {
|
||
// 读一下 lastError,避免 "Unchecked runtime.lastError" 噪音
|
||
void chrome.runtime.lastError;
|
||
});
|
||
} catch (_) { /* 扩展已重载 */ }
|
||
}
|
||
|
||
function log(message, isError) {
|
||
const prefix = '[云仓溯源] ' + location.host + ' ';
|
||
if (isError) console.warn(prefix + message);
|
||
else console.debug(prefix + message);
|
||
}
|
||
})();
|