-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
722 lines (653 loc) · 22.6 KB
/
Copy pathbackground.js
File metadata and controls
722 lines (653 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import {
MODES,
VALID_MODES,
mapAnchoredPosition,
mapAnchoredProgress,
normalizeAnchors,
validateAnchorCandidate,
} from "./lib/scroll-mapping.js";
const SESSION_KEY = "splitScrollPairsV1";
const PROFILE_KEY = "splitScrollAnchorProfilesV1";
const SPLIT_VIEW_NONE = -1;
let statePromise;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
routeMessage(message, sender)
.then((result) => sendResponse({ ok: true, ...result }))
.catch((error) => {
console.error("CoScroll Tabs:", error);
sendResponse({ ok: false, error: userFacingError(error) });
});
return true;
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.status !== "complete") {
return;
}
restoreTab(tabId).catch(() => {});
});
chrome.tabs.onRemoved.addListener((tabId) => {
removePairsContaining(tabId).catch(() => {});
});
chrome.tabs.onReplaced.addListener((addedTabId, removedTabId) => {
replaceTabInPairs(removedTabId, addedTabId).catch(() => {});
});
chrome.commands.onCommand.addListener((command) => {
if (command === "toggle-sync") {
toggleActivePair().catch(() => {});
}
});
chrome.runtime.onStartup.addListener(() => {
restoreAllPairs().catch(() => {});
});
chrome.runtime.onInstalled.addListener(() => {
restoreAllPairs().catch(() => {});
});
restoreAllPairs().catch(() => {});
async function routeMessage(message, sender) {
switch (message?.type) {
case "GET_POPUP_STATE":
return getPopupState();
case "START_PAIR":
return startPair(message.tabIds, message.mode);
case "SET_MODE":
return setPairMode(message.pairId, message.mode);
case "SET_ENABLED":
return setPairEnabled(message.pairId, Boolean(message.enabled));
case "BEGIN_ANCHOR_CALIBRATION":
return beginAnchorCalibration(message.pairId);
case "CANCEL_ANCHOR_CALIBRATION":
return cancelAnchorCalibration(message.pairId);
case "FINISH_ANCHOR_CALIBRATION":
return finishAnchorCalibration(message.pairId);
case "STOP_PAIR":
return stopPair(message.pairId);
case "ADD_ANCHOR":
return addAnchor(message.pairId);
case "REMOVE_ANCHOR":
return removeAnchor(message.pairId, message.anchorId);
case "CLEAR_ANCHORS":
return clearAnchors(message.pairId);
case "SCROLL_UPDATE":
return relayScroll(sender.tab?.id, message);
default:
throw new Error("未知操作。请重新打开扩展面板。", { cause: "UNKNOWN_MESSAGE" });
}
}
async function getState() {
if (!statePromise) {
statePromise = chrome.storage.session.get(SESSION_KEY).then((stored) => ({
pairs: Array.isArray(stored[SESSION_KEY]?.pairs)
? stored[SESSION_KEY].pairs.map(normalizePairState)
: [],
}));
}
return statePromise;
}
async function saveState(state) {
await chrome.storage.session.set({ [SESSION_KEY]: state });
}
async function getPopupState() {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!activeTab?.id) {
throw new Error("没有找到当前标签页。", { cause: "NO_ACTIVE_TAB" });
}
const allTabs = (await chrome.tabs.query({}))
.filter((tab) => Boolean(tab.incognito) === Boolean(activeTab.incognito))
.sort((left, right) => {
const leftWindowRank = left.windowId === activeTab.windowId ? 0 : 1;
const rightWindowRank = right.windowId === activeTab.windowId ? 0 : 1;
return leftWindowRank - rightWindowRank
|| left.windowId - right.windowId
|| left.index - right.index;
})
.map(toPopupTab);
const splitViewId = getSplitViewId(activeTab);
let nativeTabs = [];
if (splitViewId !== SPLIT_VIEW_NONE) {
try {
nativeTabs = (await chrome.tabs.query({ splitViewId, windowId: activeTab.windowId }))
.sort((left, right) => left.index - right.index)
.map(toPopupTab);
} catch {
nativeTabs = allTabs.filter(
(tab) => tab.windowId === activeTab.windowId && tab.splitViewId === splitViewId,
);
}
}
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.tabIds.includes(activeTab.id));
return {
activeTabId: activeTab.id,
activeWindowId: activeTab.windowId,
nativeSplitSupported: typeof activeTab.splitViewId === "number",
nativeTabs: nativeTabs.filter((tab) => tab.supported),
allTabs,
pair: pair ? await hydratePair(pair) : null,
};
}
async function startPair(rawTabIds, requestedMode) {
const tabIds = [...new Set((rawTabIds || []).map(Number).filter(Number.isInteger))];
if (tabIds.length !== 2) {
throw new Error("请选择两个不同的标签页。", { cause: "INVALID_PAIR" });
}
const mode = VALID_MODES.has(requestedMode) ? requestedMode : MODES.RATIO;
const tabs = await Promise.all(tabIds.map((tabId) => chrome.tabs.get(tabId)));
if (Boolean(tabs[0].incognito) !== Boolean(tabs[1].incognito)) {
throw new Error("普通窗口和无痕窗口不能互相联动。请在同一种浏览模式中选择两个页面。", {
cause: "DIFFERENT_PROFILES",
});
}
for (const tab of tabs) {
if (!isSupportedUrl(tab.url)) {
throw new Error(`无法在“${safeTitle(tab)}”中运行。Chrome 内部页面、扩展商店和 PDF 查看器不允许注入脚本。`, {
cause: "RESTRICTED_PAGE",
});
}
}
await Promise.all(tabIds.map(ensureContentReady));
const state = await getState();
const oldPairs = state.pairs.filter((pair) => pair.tabIds.some((tabId) => tabIds.includes(tabId)));
state.pairs = state.pairs.filter((pair) => !pair.tabIds.some((tabId) => tabIds.includes(tabId)));
const profile = await loadAnchorProfile(tabs[0].url, tabs[1].url);
const startsInAnchorCalibration = mode === MODES.ANCHORS;
const pair = {
id: globalThis.crypto.randomUUID(),
tabIds,
mode,
enabled: !startsInAnchorCalibration,
calibrating: startsInAnchorCalibration,
resumeAfterCalibration: startsInAnchorCalibration ? true : null,
modeBeforeCalibration: startsInAnchorCalibration ? MODES.RATIO : null,
calibrationStartAnchors: startsInAnchorCalibration ? normalizeAnchors(profile.anchors) : null,
anchors: profile.anchors,
profileKey: profile.key,
createdAt: Date.now(),
sequence: 0,
};
state.pairs.push(pair);
await saveState(state);
await Promise.all(
oldPairs.flatMap((oldPair) => oldPair.tabIds.flatMap((tabId) => [configureTab(tabId, null), clearBadge(tabId)])),
);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function setPairMode(pairId, mode) {
if (!VALID_MODES.has(mode)) {
throw new Error("不支持这种联动模式。", { cause: "INVALID_MODE" });
}
if (mode === MODES.ANCHORS) {
return beginAnchorCalibration(pairId);
}
let restoredCalibration = false;
const pair = await mutatePair(pairId, (current) => {
restoredCalibration = Boolean(current.calibrating);
return {
...current,
mode,
enabled: current.calibrating ? Boolean(current.resumeAfterCalibration) : current.enabled,
anchors: current.calibrating
? normalizeAnchors(current.calibrationStartAnchors || [])
: current.anchors,
calibrating: false,
resumeAfterCalibration: null,
modeBeforeCalibration: null,
calibrationStartAnchors: null,
};
});
if (restoredCalibration) {
await saveAnchorProfile(pair.profileKey, pair.anchors);
}
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function setPairEnabled(pairId, enabled) {
const state = await getState();
const current = findPair(state, pairId);
if (enabled && current.calibrating) {
return finishAnchorCalibration(pairId);
}
if (enabled && current.mode === MODES.ANCHORS && !normalizeAnchors(current.anchors).length) {
throw new Error("请先记录至少一个关联点,再开启联动。", { cause: "ANCHORS_REQUIRED" });
}
const pair = await mutatePair(pairId, (current) => ({
...current,
enabled,
}));
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function beginAnchorCalibration(pairId) {
const pair = await mutatePair(pairId, (current) => {
if (current.calibrating) {
return current;
}
return {
...current,
mode: MODES.ANCHORS,
enabled: false,
calibrating: true,
resumeAfterCalibration: Boolean(current.enabled),
modeBeforeCalibration: current.mode,
calibrationStartAnchors: normalizeAnchors(current.anchors),
};
});
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function cancelAnchorCalibration(pairId) {
const state = await getState();
const pair = findPair(state, pairId);
if (!pair.calibrating) {
return { pair: await hydratePair(pair) };
}
pair.anchors = normalizeAnchors(pair.calibrationStartAnchors || []);
pair.mode = VALID_MODES.has(pair.modeBeforeCalibration) ? pair.modeBeforeCalibration : MODES.ANCHORS;
pair.enabled = Boolean(pair.resumeAfterCalibration)
&& (pair.mode !== MODES.ANCHORS || pair.anchors.length > 0);
pair.calibrating = false;
pair.resumeAfterCalibration = null;
pair.modeBeforeCalibration = null;
pair.calibrationStartAnchors = null;
await saveState(state);
await saveAnchorProfile(pair.profileKey, pair.anchors);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function finishAnchorCalibration(pairId) {
const state = await getState();
const pair = findPair(state, pairId);
if (!pair.calibrating) {
return { pair: await hydratePair(pair) };
}
pair.anchors = normalizeAnchors(pair.anchors);
if (!pair.anchors.length) {
throw new Error("请先记录至少一个关联点,再完成校准。", { cause: "ANCHORS_REQUIRED" });
}
pair.mode = MODES.ANCHORS;
pair.enabled = Boolean(pair.resumeAfterCalibration);
pair.calibrating = false;
pair.resumeAfterCalibration = null;
pair.modeBeforeCalibration = null;
pair.calibrationStartAnchors = null;
await saveState(state);
await saveAnchorProfile(pair.profileKey, pair.anchors);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function stopPair(pairId) {
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.id === pairId);
if (!pair) {
return { stopped: true };
}
state.pairs = state.pairs.filter((candidate) => candidate.id !== pairId);
await saveState(state);
await Promise.all(pair.tabIds.map((tabId) => configureTab(tabId, null)));
await Promise.all(pair.tabIds.map((tabId) => clearBadge(tabId)));
return { stopped: true };
}
async function addAnchor(pairId) {
const state = await getState();
const pair = findPair(state, pairId);
if (!pair.calibrating || pair.mode !== MODES.ANCHORS) {
throw new Error("请先进入关联点校准,再记录位置。", { cause: "CALIBRATION_REQUIRED" });
}
const positions = await Promise.all(pair.tabIds.map(readScrollState));
const result = validateAnchorCandidate(pair.anchors, {
a: positions[0].progress,
b: positions[1].progress,
aTop: positions[0].scrollTop,
bTop: positions[1].scrollTop,
aMax: positions[0].maxScroll,
bMax: positions[1].maxScroll,
});
if (!result.ok) {
throw new Error(result.error, { cause: "ANCHOR_CONFLICT" });
}
pair.anchors = result.anchors;
await saveState(state);
await saveAnchorProfile(pair.profileKey, pair.anchors);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function removeAnchor(pairId, anchorId) {
const state = await getState();
const pair = findPair(state, pairId);
pair.anchors = normalizeAnchors(pair.anchors).filter((anchor) => anchor.id !== anchorId);
enterCalibrationIfAnchorsEmpty(pair);
await saveState(state);
await saveAnchorProfile(pair.profileKey, pair.anchors);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function clearAnchors(pairId) {
const state = await getState();
const pair = findPair(state, pairId);
pair.anchors = [];
enterCalibrationIfAnchorsEmpty(pair);
await saveState(state);
await saveAnchorProfile(pair.profileKey, []);
await broadcastPair(pair);
await updatePairBadges(pair);
return { pair: await hydratePair(pair) };
}
async function relayScroll(sourceTabId, update) {
if (!sourceTabId) {
return { relayed: false };
}
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.tabIds.includes(sourceTabId));
if (!pair?.enabled || update.pairId !== pair.id) {
return { relayed: false };
}
const sourceIndex = pair.tabIds.indexOf(sourceTabId);
const targetTabId = pair.tabIds[sourceIndex === 0 ? 1 : 0];
pair.sequence = (pair.sequence || 0) + 1;
const payload = {
type: "APPLY_SCROLL",
pairId: pair.id,
sequence: pair.sequence,
mode: pair.mode,
};
if (pair.mode === MODES.DELTA) {
payload.delta = Number(update.delta) || 0;
} else if (pair.mode === MODES.ANCHORS) {
if (update.boundary === "start" || update.boundary === "end") {
payload.boundary = update.boundary;
} else {
const mappedPosition = mapAnchoredPosition(update.scrollTop, pair.anchors, sourceIndex === 1);
if (Number.isFinite(mappedPosition)) {
payload.position = mappedPosition;
} else {
const mapped = mapAnchoredProgress(update.progress, pair.anchors, sourceIndex === 1);
if (!Number.isFinite(mapped)) {
return { relayed: false, reason: "ANCHORS_REQUIRED" };
}
payload.progress = mapped;
}
if (!Number.isFinite(payload.position) && !Number.isFinite(payload.progress)) {
return { relayed: false, reason: "ANCHORS_REQUIRED" };
}
}
} else {
payload.progress = Math.min(1, Math.max(0, Number(update.progress) || 0));
}
try {
await chrome.tabs.sendMessage(targetTabId, payload);
return { relayed: true };
} catch {
try {
await ensureContentReady(targetTabId);
await configureTab(targetTabId, pair);
await chrome.tabs.sendMessage(targetTabId, payload);
return { relayed: true };
} catch {
return { relayed: false };
}
}
}
function normalizePairState(pair) {
const anchors = normalizeAnchors(pair?.anchors);
const calibrating = Boolean(pair?.calibrating);
const anchorModeWithoutMapping = pair?.mode === MODES.ANCHORS && !anchors.length && !calibrating;
return {
...pair,
anchors,
enabled: calibrating || anchorModeWithoutMapping ? false : Boolean(pair?.enabled),
calibrating,
resumeAfterCalibration: calibrating ? Boolean(pair?.resumeAfterCalibration) : null,
modeBeforeCalibration: calibrating && VALID_MODES.has(pair?.modeBeforeCalibration)
? pair.modeBeforeCalibration
: null,
calibrationStartAnchors: calibrating
? normalizeAnchors(Array.isArray(pair?.calibrationStartAnchors) ? pair.calibrationStartAnchors : anchors)
: null,
};
}
function enterCalibrationIfAnchorsEmpty(pair) {
if (pair.mode !== MODES.ANCHORS || pair.calibrating || normalizeAnchors(pair.anchors).length) {
return;
}
const wasEnabled = Boolean(pair.enabled);
pair.enabled = false;
pair.calibrating = true;
pair.resumeAfterCalibration = wasEnabled;
pair.modeBeforeCalibration = MODES.ANCHORS;
pair.calibrationStartAnchors = [];
}
async function mutatePair(pairId, updater) {
const state = await getState();
const index = state.pairs.findIndex((pair) => pair.id === pairId);
if (index < 0) {
throw new Error("这个联动已经失效,请重新连接。", { cause: "PAIR_NOT_FOUND" });
}
state.pairs[index] = updater(state.pairs[index]);
await saveState(state);
return state.pairs[index];
}
function findPair(state, pairId) {
const pair = state.pairs.find((candidate) => candidate.id === pairId);
if (!pair) {
throw new Error("这个联动已经失效,请重新连接。", { cause: "PAIR_NOT_FOUND" });
}
return pair;
}
async function hydratePair(pair) {
const tabs = await Promise.all(
pair.tabIds.map(async (tabId) => {
try {
return toPopupTab(await chrome.tabs.get(tabId));
} catch {
return { id: tabId, title: "已关闭的标签页", domain: "", supported: false };
}
}),
);
return { ...pair, tabs, anchors: normalizeAnchors(pair.anchors) };
}
async function ensureContentReady(tabId) {
try {
const response = await chrome.tabs.sendMessage(tabId, { type: "PING" });
if (response?.ready) {
return;
}
} catch {}
await chrome.scripting.executeScript({
target: { tabId },
files: ["content.js"],
});
const response = await chrome.tabs.sendMessage(tabId, { type: "PING" });
if (!response?.ready) {
throw new Error("页面脚本没有响应。", { cause: "CONTENT_NOT_READY" });
}
}
async function readScrollState(tabId) {
await ensureContentReady(tabId);
const response = await chrome.tabs.sendMessage(tabId, { type: "GET_SCROLL_STATE" });
if (!response?.state) {
throw new Error("无法读取页面滚动位置。", { cause: "NO_SCROLL_STATE" });
}
return response.state;
}
async function broadcastPair(pair) {
await Promise.all(pair.tabIds.map((tabId) => configureTab(tabId, pair)));
}
async function configureTab(tabId, pair) {
try {
if (pair) {
await ensureContentReady(tabId);
}
await chrome.tabs.sendMessage(tabId, {
type: "CONFIGURE",
config: pair
? {
pairId: pair.id,
enabled: pair.enabled,
mode: pair.mode,
}
: null,
});
} catch {}
}
async function restoreTab(tabId) {
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.tabIds.includes(tabId));
if (pair) {
await configureTab(tabId, pair);
await updatePairBadges(pair);
}
}
async function restoreAllPairs() {
const state = await getState();
await Promise.all(state.pairs.map(async (pair) => {
await broadcastPair(pair);
await updatePairBadges(pair);
}));
}
async function removePairsContaining(tabId) {
const state = await getState();
const removed = state.pairs.filter((pair) => pair.tabIds.includes(tabId));
if (!removed.length) {
return;
}
state.pairs = state.pairs.filter((pair) => !pair.tabIds.includes(tabId));
await saveState(state);
await Promise.all(
removed.flatMap((pair) => pair.tabIds
.filter((id) => id !== tabId)
.flatMap((id) => [configureTab(id, null), clearBadge(id)])),
);
}
async function replaceTabInPairs(removedTabId, addedTabId) {
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.tabIds.includes(removedTabId));
if (!pair) {
return;
}
pair.tabIds = pair.tabIds.map((tabId) => (tabId === removedTabId ? addedTabId : tabId));
await saveState(state);
await configureTab(addedTabId, pair);
await updatePairBadges(pair);
}
async function toggleActivePair() {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!activeTab?.id) {
return;
}
const state = await getState();
const pair = state.pairs.find((candidate) => candidate.tabIds.includes(activeTab.id));
if (pair && !pair.calibrating) {
await setPairEnabled(pair.id, !pair.enabled);
}
}
async function updatePairBadges(pair) {
const text = pair.calibrating ? "SET" : pair.enabled ? "ON" : "Ⅱ";
const color = pair.calibrating || pair.enabled ? "#1769aa" : "#667085";
await Promise.all(pair.tabIds.map(async (tabId) => {
try {
await chrome.action.setBadgeBackgroundColor({ tabId, color });
await chrome.action.setBadgeText({ tabId, text });
} catch {}
}));
}
async function clearBadge(tabId) {
try {
await chrome.action.setBadgeText({ tabId, text: "" });
} catch {}
}
async function loadAnchorProfile(urlA, urlB) {
const directKey = await hashPair(urlA, urlB);
const reverseKey = await hashPair(urlB, urlA);
const stored = await chrome.storage.local.get(PROFILE_KEY);
const profiles = stored[PROFILE_KEY] || {};
if (Array.isArray(profiles[directKey])) {
return { key: directKey, anchors: normalizeAnchors(profiles[directKey]) };
}
if (Array.isArray(profiles[reverseKey])) {
return {
key: directKey,
anchors: normalizeAnchors(profiles[reverseKey]).map((anchor) => ({ ...anchor, a: anchor.b, b: anchor.a })),
};
}
return { key: directKey, anchors: [] };
}
async function saveAnchorProfile(key, anchors) {
if (!key) {
return;
}
const stored = await chrome.storage.local.get(PROFILE_KEY);
const profiles = stored[PROFILE_KEY] || {};
profiles[key] = normalizeAnchors(anchors);
await chrome.storage.local.set({ [PROFILE_KEY]: profiles });
}
async function hashPair(urlA, urlB) {
const normalized = `${normalizeUrl(urlA)}\n${normalizeUrl(urlB)}`;
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(normalized));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}
function normalizeUrl(value) {
try {
const url = new URL(value);
url.hash = "";
return url.href;
} catch {
return String(value || "");
}
}
function getSplitViewId(tab) {
return typeof tab?.splitViewId === "number" && tab.splitViewId !== (chrome.tabs.SPLIT_VIEW_ID_NONE ?? SPLIT_VIEW_NONE)
? tab.splitViewId
: SPLIT_VIEW_NONE;
}
function toPopupTab(tab) {
return {
id: tab.id,
windowId: tab.windowId,
index: tab.index,
active: tab.active,
incognito: Boolean(tab.incognito),
title: safeTitle(tab),
domain: domainFromUrl(tab.url),
url: tab.url || "",
splitViewId: getSplitViewId(tab),
supported: isSupportedUrl(tab.url),
};
}
function safeTitle(tab) {
return (tab.title || domainFromUrl(tab.url) || `标签页 ${tab.id}`).trim().slice(0, 100);
}
function domainFromUrl(value) {
try {
const url = new URL(value);
return url.protocol === "file:" ? "本地文件" : url.hostname;
} catch {
return "";
}
}
function isSupportedUrl(value) {
if (!value) {
return false;
}
if (/\.pdf(?:$|[?#])/i.test(value)) {
return false;
}
if (/^https?:\/\/(?:chromewebstore\.google\.com|chrome\.google\.com\/webstore|microsoftedge\.microsoft\.com\/addons)/i.test(value)) {
return false;
}
return /^(https?:|file:)/i.test(value);
}
function userFacingError(error) {
const message = error?.message || String(error || "操作失败。请重试。");
if (/Cannot access|The extensions gallery cannot be scripted|Missing host permission|Frame with ID/i.test(message)) {
return "Chrome 不允许扩展访问这个页面。请改用普通网页,或在本地文件页面启用“允许访问文件网址”。";
}
return message;
}