-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-current-url.user.js
More file actions
430 lines (362 loc) · 15.6 KB
/
copy-current-url.user.js
File metadata and controls
430 lines (362 loc) · 15.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
// ==UserScript==
// @name 複製當前網址
// @namespace https://chris.taipei
// @version 0.4.1
// @description 按下 Ctrl+Shift+C 複製當前網址(X/Twitter 轉 fxTwitter,PChome 轉 Pancake,Shopee 轉短網址)
// @author chris1004tw
// @match *://*/*
// @grant GM_setClipboard
// @run-at document-end
// @updateURL https://github.com/chris1004tw/userscripts/raw/main/copy-current-url.user.js
// @downloadURL https://github.com/chris1004tw/userscripts/raw/main/copy-current-url.user.js
// ==/UserScript==
// Co-authored with Claude Opus 4.6 Thinking
// Shopee 短網址轉換參考自 https://github.com/gnehs/userscripts
// PChome 短網址服務由 https://p.pancake.tw/ 提供
// X/Twitter 短網址服務由 https://fxtwitter.com/ 提供
(function () {
'use strict';
// X/Twitter 功能的延遲常數
const DELAY_INITIAL = 1000;
const DELAY_RETRY = 2000;
const DELAY_DEBOUNCE = 500;
const NOTIFICATION_DURATION = 2000;
const TWEET_ACTION_GROUP_SELECTOR = 'div[role="group"]';
const TWEET_RELEVANT_SELECTOR = `article, ${TWEET_ACTION_GROUP_SELECTOR}`;
// debounce 計時器(閉包變數,避免全域汙染)
let fxTwitterTimeout;
const pendingTweetRoots = new Set();
let pendingFullTweetScan = false;
// 只在主框架執行,避免 iframe 內重複顯示通知
try {
if (window.self !== window.top) return;
} catch {
// 跨域 iframe 中存取 window.top 可能拋出 SecurityError,視為 iframe 跳過
return;
}
// 等待 body 存在
function waitForBody() {
return new Promise((resolve) => {
if (document.body) {
resolve();
return;
}
let timeoutId;
const observer = new MutationObserver(() => {
if (document.body) {
clearTimeout(timeoutId);
observer.disconnect();
resolve();
}
});
observer.observe(document.documentElement, { childList: true });
timeoutId = setTimeout(() => {
observer.disconnect();
resolve();
}, 5000);
});
}
// 確保動畫樣式存在
function ensureStyleExists() {
if (document.getElementById('copy-url-notification-style')) {
return;
}
const style = document.createElement('style');
style.id = 'copy-url-notification-style';
style.textContent = `
@keyframes copyUrlFadeInOut {
0% { opacity: 0; transform: translateY(-10px); }
15% { opacity: 1; transform: translateY(0); }
85% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(-10px); }
}
`;
(document.head || document.documentElement).appendChild(style);
}
// 顯示通知
async function showNotification(url, title = '已複製網址!') {
try {
await waitForBody();
ensureStyleExists();
const notification = document.createElement('div');
// 使用 DOM API 而非 innerHTML,避免 Trusted Types CSP 問題
const titleDiv = document.createElement('div');
titleDiv.textContent = title;
titleDiv.style.cssText = 'font-weight: bold; margin-bottom: 4px;';
const urlDiv = document.createElement('div');
urlDiv.textContent = url;
urlDiv.style.cssText = 'font-size: 12px; opacity: 0.8; word-break: break-all;';
notification.appendChild(titleDiv);
notification.appendChild(urlDiv);
notification.style.cssText = `
position: fixed !important;
top: 20px !important;
right: 20px !important;
background-color: #000 !important;
color: #fff !important;
padding: 12px 20px !important;
border-radius: 8px !important;
z-index: 2147483647 !important;
font-size: 14px !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
animation: copyUrlFadeInOut ${NOTIFICATION_DURATION / 1000}s ease-in-out !important;
max-width: 400px !important;
pointer-events: none !important;
`;
document.body.appendChild(notification);
setTimeout(() => {
if (notification.parentNode) {
notification.remove();
}
}, NOTIFICATION_DURATION);
} catch (err) {
// 通知顯示失敗不影響複製功能
console.warn('[Copy URL] 通知顯示失敗:', err);
}
}
// 檢查是否為 X/Twitter 網站
function isXTwitter() {
const host = window.location.hostname;
return host === 'x.com' || host === 'twitter.com' ||
host === 'www.x.com' || host === 'www.twitter.com';
}
// 將 X/Twitter 網址轉換為 fxTwitter
// 嵌入修復服務由 https://fxtwitter.com/ 提供
function convertToFxTwitter(url) {
return url
.replace(/https?:\/\/(www\.)?x\.com/, 'https://fxtwitter.com')
.replace(/https?:\/\/(www\.)?twitter\.com/, 'https://fxtwitter.com');
}
// 檢查是否為 Shopee 網站
function isShopee() {
return window.location.hostname === 'shopee.tw';
}
// 將 Shopee 網址轉換為短網址
// 參考自 https://github.com/gnehs/userscripts
function convertToShopeeShort(url) {
const parsed = new URL(url);
// 取路徑最後一段,以 - 分隔
const pathParts = parsed.pathname.split('-');
const lastPart = pathParts[pathParts.length - 1];
// 檢查是否為 i.shopId.itemId 格式
const shopeePath = lastPart.split('.');
if (shopeePath[0] === 'i' && shopeePath.length === 3) {
return 'https://shopee.tw/product/' + shopeePath[1] + '/' + shopeePath[2];
}
// 非商品頁面,回傳原網址
return url;
}
// 檢查是否為 PChome 24h 網站
function isPChome24h() {
return window.location.hostname === '24h.pchome.com.tw';
}
// 將 PChome 24h 網址轉換為 pancake.tw 短網址
// 短網址服務由 https://p.pancake.tw/ 提供
function convertToPancake(url) {
// 只處理商品頁面 /prod/xxx
const match = url.match(/^https?:\/\/24h\.pchome\.com\.tw(\/prod\/[^?#]+)/);
if (match) {
return 'https://p.pancake.tw' + match[1];
}
// 非商品頁面,回傳原網址
return url;
}
// 複製網址並顯示通知
function copyCurrentUrl() {
let url = window.location.href;
let notificationTitle = '已複製網址!';
if (isXTwitter()) {
url = convertToFxTwitter(url);
notificationTitle = '已複製 fxTwitter 網址!';
} else if (isShopee()) {
const shortUrl = convertToShopeeShort(url);
if (shortUrl !== url) {
url = shortUrl;
notificationTitle = '已複製 Shopee 短網址!';
}
} else if (isPChome24h()) {
const shortUrl = convertToPancake(url);
if (shortUrl !== url) {
url = shortUrl;
notificationTitle = '已複製 PChome Pancake 網址!';
}
}
GM_setClipboard(url, 'text');
showNotification(url, notificationTitle);
}
// ========== X/Twitter 專屬功能(按鈕) ==========
// 檢查是否在單篇推文頁面
function isStatusPage() {
return /\/(status|statuses)\/\d+/.test(window.location.pathname);
}
// 創建內嵌按鈕(模仿 X.com 分享按鈕樣式)
const BUTTON_COLOR = 'rgb(113, 118, 123)';
const BUTTON_HOVER_COLOR = 'rgb(29, 155, 240)';
const BUTTON_HOVER_BG = 'rgba(29, 155, 240, 0.1)';
function createInlineButton() {
const outerContainer = document.createElement('div');
outerContainer.setAttribute('class', 'css-175oi2r');
outerContainer.style.cssText = 'justify-content: inherit; display: inline-grid; transform: rotate(0deg) scale(1) translate3d(0px, 0px, 0px);';
const innerContainer = document.createElement('div');
innerContainer.setAttribute('class', 'css-175oi2r r-18u37iz r-1h0z5md');
const button = document.createElement('button');
button.setAttribute('aria-label', '複製 fxTwitter 連結');
button.setAttribute('role', 'button');
button.setAttribute('class', 'css-175oi2r r-1777fci r-bt1l66 r-bztko3 r-lrvibr r-1loqt21 r-1ny4l3l');
button.type = 'button';
button.setAttribute('title', '複製 fxTwitter 連結');
const buttonContent = document.createElement('div');
buttonContent.setAttribute('dir', 'ltr');
buttonContent.setAttribute('class', 'css-146c3p1 r-bcqeeo r-1ttztb7 r-qvutc0 r-37j5jr r-a023e6 r-rjixqe r-16dba41 r-1awozwy r-6koalj r-1h0z5md r-o7ynqc r-clp7b1 r-3s2u2q');
buttonContent.style.color = BUTTON_COLOR;
const iconContainer = document.createElement('div');
iconContainer.setAttribute('class', 'css-175oi2r r-xoduu5');
const iconBackground = document.createElement('div');
iconBackground.setAttribute('class', 'css-175oi2r r-xoduu5 r-1p0dtai r-1d2f490 r-u8s1d r-zchlnj r-ipm5af r-1niwhzg r-sdzlij r-xf4iuw r-o7ynqc r-6416eg r-1ny4l3l');
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('class', 'r-4qtqp9 r-yyyyoo r-dnmrzs r-bnwqim r-lrvibr r-m6rgpd r-50lct3 r-1srniue');
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z');
g.appendChild(path);
svg.appendChild(g);
iconContainer.appendChild(iconBackground);
iconContainer.appendChild(svg);
buttonContent.appendChild(iconContainer);
button.appendChild(buttonContent);
innerContainer.appendChild(button);
outerContainer.appendChild(innerContainer);
// 懸停效果
button.addEventListener('mouseenter', () => {
buttonContent.style.color = BUTTON_HOVER_COLOR;
iconBackground.style.backgroundColor = BUTTON_HOVER_BG;
});
button.addEventListener('mouseleave', () => {
buttonContent.style.color = BUTTON_COLOR;
iconBackground.style.backgroundColor = '';
});
button.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
copyCurrentUrl();
});
return outerContainer;
}
// 添加按鈕到推文操作區域
const processedGroups = new WeakSet();
function processActionGroup(group) {
if (processedGroups.has(group)) return;
const hasReply = group.querySelector('[data-testid="reply"]');
const hasRetweet = group.querySelector('[data-testid="retweet"]');
const hasLike = group.querySelector('[data-testid="like"]');
const hasShare = group.querySelector('[data-testid="share"]');
const actionCount = [hasReply, hasRetweet, hasLike, hasShare].filter(Boolean).length;
if (actionCount >= 2) {
group.appendChild(createInlineButton());
}
processedGroups.add(group);
}
function collectActionGroupsFromRoot(root, groups) {
if (!root || root.nodeType !== Node.ELEMENT_NODE) return;
if (root.matches?.(TWEET_ACTION_GROUP_SELECTOR)) {
groups.add(root);
}
const nestedGroups = root.querySelectorAll?.(TWEET_ACTION_GROUP_SELECTOR);
if (!nestedGroups) return;
nestedGroups.forEach(group => groups.add(group));
}
function scheduleTweetScan(full = false) {
if (full) {
pendingFullTweetScan = true;
pendingTweetRoots.clear();
}
clearTimeout(fxTwitterTimeout);
fxTwitterTimeout = setTimeout(() => {
const roots = pendingFullTweetScan ? null : Array.from(pendingTweetRoots);
pendingTweetRoots.clear();
pendingFullTweetScan = false;
addButtonToTweets(roots);
}, DELAY_DEBOUNCE);
}
function isRelevantTweetNode(node) {
return node.nodeType === Node.ELEMENT_NODE &&
(node.matches?.(TWEET_RELEVANT_SELECTOR) ||
node.querySelector?.(TWEET_RELEVANT_SELECTOR));
}
function addButtonToTweets(roots = null) {
if (!isStatusPage()) return;
if (!roots) {
document.querySelectorAll(TWEET_ACTION_GROUP_SELECTOR).forEach(processActionGroup);
return;
}
const groups = new Set();
roots.forEach(root => collectActionGroupsFromRoot(root, groups));
groups.forEach(processActionGroup);
}
// 初始化 X/Twitter 專屬功能
function initXTwitterFeatures() {
// 初始添加按鈕
setTimeout(() => addButtonToTweets(), DELAY_INITIAL);
setTimeout(() => addButtonToTweets(), DELAY_RETRY);
// MutationObserver 監聽頁面變化
const observer = new MutationObserver((mutations) => {
let shouldUpdate = false;
for (const mutation of mutations) {
if (mutation.type !== 'childList') continue;
for (const node of mutation.addedNodes) {
if (!isRelevantTweetNode(node)) continue;
pendingTweetRoots.add(node);
shouldUpdate = true;
}
}
if (shouldUpdate) {
scheduleTweetScan();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
// 攔截 history API 偵測 SPA 導航(取代 setInterval 輪詢)
let lastUrl = location.href;
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
function onUrlChange() {
if (location.href !== lastUrl) {
lastUrl = location.href;
scheduleTweetScan(true);
}
}
history.pushState = function (...args) {
originalPushState.apply(this, args);
onUrlChange();
};
history.replaceState = function (...args) {
originalReplaceState.apply(this, args);
onUrlChange();
};
window.addEventListener('popstate', onUrlChange);
// 頁面卸載時清理 MutationObserver
window.addEventListener('beforeunload', () => {
observer.disconnect();
clearTimeout(fxTwitterTimeout);
});
}
// ========== 初始化 ==========
// 監聽鍵盤事件(所有網站)
document.addEventListener('keydown', function (e) {
// Ctrl+Shift+C
if (e.ctrlKey && e.shiftKey && e.code === 'KeyC') {
e.preventDefault();
e.stopPropagation();
copyCurrentUrl();
}
}, true);
// X/Twitter 專屬功能(按鈕 + MutationObserver)
if (isXTwitter()) {
initXTwitterFeatures();
}
})();