Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
329 lines (278 loc) · 9.98 KB
/
Copy pathcontent.js
File metadata and controls
329 lines (278 loc) · 9.98 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
// Better Tab Split - Content Script
// 拦截链接点击并在另一个 Split View 中打开
(function () {
'use strict';
// 防止重复注入
if (window.__betterTabSplitInjected) {
return;
}
window.__betterTabSplitInjected = true;
let isEnabled = false;
// 用于跟踪已处理的 mousedown 事件,避免 click 事件重复处理
let pendingNavigation = null;
// 查找链接元素
function findLinkElement(element) {
let target = element;
// 向上遍历 DOM 树查找 <a> 标签
while (target && target !== document.body) {
if (target.tagName === 'A' && target.href) {
return target;
}
// 也检查 data-href 或其他常见的链接属性(用于 SPA)
if (target.dataset && target.dataset.href) {
return { href: target.dataset.href, isDataAttr: true };
}
target = target.parentElement;
}
return null;
}
// 检查 URL 是否有效(用于导航)
function isValidUrl(url) {
if (!url) return false;
// 必须是 http 或 https 协议
if (!url.startsWith('http://') && !url.startsWith('https://')) {
return false;
}
// 排除只有锚点的链接(如 https://example.com/#)
try {
const urlObj = new URL(url);
const currentUrl = new URL(window.location.href);
// 如果只是锚点不同,不算有效的导航链接
if (urlObj.origin === currentUrl.origin &&
urlObj.pathname === currentUrl.pathname &&
urlObj.search === currentUrl.search) {
return false;
}
} catch (e) {
return false;
}
return true;
}
// 检查链接是否是 UI 控件(不应该被拦截)
function isUIControlLink(element) {
if (!element || element.isDataAttr) return false;
// 检查常见的 UI 控件属性(Bootstrap, AdminLTE 等框架使用)
const uiAttributes = [
'data-widget', // AdminLTE 侧边栏控件
'data-toggle', // Bootstrap 切换控件
'data-bs-toggle', // Bootstrap 5 切换控件
'data-action', // 通用操作属性
'data-slide', // 轮播控件
'data-bs-slide', // Bootstrap 5 轮播
'data-dismiss', // 关闭按钮
'data-bs-dismiss', // Bootstrap 5 关闭按钮
'data-target', // 目标元素(通常用于模态框等)
'data-bs-target', // Bootstrap 5 目标元素
];
for (const attr of uiAttributes) {
if (element.hasAttribute(attr)) {
return true;
}
}
// 检查 role 属性
const role = element.getAttribute('role');
if (role && ['button', 'tab', 'menuitem', 'switch'].includes(role)) {
return true;
}
// 检查 href 是否是 javascript: 协议或只是 #
const href = element.getAttribute('href');
if (href === '#' || href === '' || (href && href.startsWith('javascript:'))) {
return true;
}
return false;
}
// 检查是否应该拦截此事件
function shouldIntercept(event, linkElement) {
if (!isEnabled) return false;
if (!linkElement) return false;
// 检查是否是 UI 控件链接(如汉堡按钮、模态框触发器等)
if (isUIControlLink(linkElement)) {
return false;
}
const url = linkElement.href;
if (!isValidUrl(url)) return false;
// 检查是否有特殊的 target 属性(如 _self)
if (!linkElement.isDataAttr) {
const targetAttr = linkElement.getAttribute('target');
if (targetAttr === '_self') {
return false; // 尊重 _self,在当前页面打开
}
}
// 检查是否按住了修饰键
if (event.ctrlKey || event.metaKey || event.shiftKey) {
return false; // 让浏览器处理修饰键组合
}
// 检查是否是中键点击
if (event.button !== 0) {
return false; // 只处理左键点击
}
return true;
}
// 执行导航到另一个 Split View
function navigateToOtherSplit(url) {
chrome.runtime.sendMessage({
type: 'OPEN_IN_OTHER_SPLIT',
url: url
}).catch(err => {
console.error('Better Tab Split: Error sending message:', err);
// 如果发送失败,使用默认行为
window.open(url, '_blank');
});
}
// 处理 mousedown/pointerdown 事件 - 在 click 之前捕获
// 这对于 React/SPA 网站很重要,因为它们可能在 click 事件中使用 stopPropagation
function handleMouseDown(event) {
const linkElement = findLinkElement(event.target);
if (!shouldIntercept(event, linkElement)) {
pendingNavigation = null;
return;
}
// 记录待处理的导航
pendingNavigation = {
url: linkElement.href,
timestamp: Date.now(),
target: event.target
};
// 对于 SPA 网站,我们需要在 mousedown 阶段就阻止事件传播
// 这样可以防止 React 等框架的事件处理器处理这个点击
// 注意:我们不在这里调用 preventDefault(),因为这会影响焦点等行为
event.stopPropagation();
event.stopImmediatePropagation();
}
// 处理 click 事件
function handleClick(event) {
const linkElement = findLinkElement(event.target);
// 如果有待处理的导航且时间间隔合理(500ms 内)
if (pendingNavigation && Date.now() - pendingNavigation.timestamp < 500) {
const url = pendingNavigation.url;
pendingNavigation = null;
// 阻止所有其他事件处理器
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
navigateToOtherSplit(url);
return;
}
// 清除过期的待处理导航
pendingNavigation = null;
// 作为备份,也直接检查 click 事件
if (!shouldIntercept(event, linkElement)) {
return;
}
// 阻止所有其他事件处理器
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
navigateToOtherSplit(linkElement.href);
}
// 处理 auxclick 事件(中键点击等)- 不拦截,让浏览器处理
// 这里不需要特殊处理
// 添加事件监听器
function enableLinkInterception() {
// 使用捕获阶段,确保在其他处理器之前执行
// 同时监听 pointerdown 和 mousedown,因为某些框架可能使用 pointer events
document.addEventListener('pointerdown', handleMouseDown, true);
document.addEventListener('mousedown', handleMouseDown, true);
document.addEventListener('click', handleClick, true);
}
// 移除事件监听器
function disableLinkInterception() {
document.removeEventListener('pointerdown', handleMouseDown, true);
document.removeEventListener('mousedown', handleMouseDown, true);
document.removeEventListener('click', handleClick, true);
}
// === History API 拦截 ===
// 用于处理 SPA 的客户端导航(如 React Router)
let historyInterceptionEnabled = false;
const originalPushState = history.pushState.bind(history);
const originalReplaceState = history.replaceState.bind(history);
// 检查 URL 是否是同源的不同页面
function isDifferentPage(url) {
try {
const newUrl = new URL(url, window.location.origin);
const currentUrl = new URL(window.location.href);
// 检查是否是同源
if (newUrl.origin !== currentUrl.origin) {
return false; // 跨域,不处理
}
// 检查路径是否不同
return newUrl.pathname !== currentUrl.pathname;
} catch (e) {
return false;
}
}
// 拦截 history.pushState
function interceptedPushState(state, title, url) {
if (historyInterceptionEnabled && isEnabled && url && isDifferentPage(url)) {
// 检查这是否是由用户点击触发的(通过检查 pendingNavigation)
if (pendingNavigation && Date.now() - pendingNavigation.timestamp < 500) {
const fullUrl = new URL(url, window.location.origin).href;
pendingNavigation = null;
// 在另一个 Split View 中打开,不在当前页面导航
navigateToOtherSplit(fullUrl);
return; // 不执行原始的 pushState
}
}
// 执行原始的 pushState
return originalPushState(state, title, url);
}
// 拦截 history.replaceState
function interceptedReplaceState(state, title, url) {
if (historyInterceptionEnabled && isEnabled && url && isDifferentPage(url)) {
if (pendingNavigation && Date.now() - pendingNavigation.timestamp < 500) {
const fullUrl = new URL(url, window.location.origin).href;
pendingNavigation = null;
navigateToOtherSplit(fullUrl);
return;
}
}
return originalReplaceState(state, title, url);
}
// 启用 History API 拦截
function enableHistoryInterception() {
if (historyInterceptionEnabled) return;
historyInterceptionEnabled = true;
history.pushState = interceptedPushState;
history.replaceState = interceptedReplaceState;
}
// 禁用 History API 拦截
function disableHistoryInterception() {
if (!historyInterceptionEnabled) return;
historyInterceptionEnabled = false;
history.pushState = originalPushState;
history.replaceState = originalReplaceState;
}
// 更新后的启用/禁用函数
function enableAllInterception() {
enableLinkInterception();
enableHistoryInterception();
}
function disableAllInterception() {
disableLinkInterception();
disableHistoryInterception();
}
// 监听来自 background script 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'UPDATE_STATE') {
isEnabled = message.enabled;
if (isEnabled) {
enableAllInterception();
} else {
disableAllInterception();
}
sendResponse({ success: true });
}
return true;
});
// 初始化时检查状态
chrome.runtime.sendMessage({ type: 'CHECK_ENABLED' })
.then(response => {
if (response && response.enabled) {
isEnabled = true;
enableAllInterception();
}
})
.catch(err => {
console.error('Better Tab Split: Error checking initial state:', err);
});
})();