-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
706 lines (621 loc) · 23.6 KB
/
content.js
File metadata and controls
706 lines (621 loc) · 23.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
/**
* TubeSnap - Content Script
* 一键截取 YouTube 视频画面
*/
'use strict';
// ===== 配置与状态 =====
const CONFIG = {
screenshotFormat: 'png',
screenshotQuality: 0.95,
screenshotAction: 'both',
enableWatermark: false,
watermarkPosition: 'bottom-right',
watermarkStyle: 'simple', // 'simple' | 'frame'
};
let isAppended = false;
let screenshotButton = null;
// ===== DOM 选择器 =====
const SELECTORS = {
video: 'video.html5-main-video, video[src*="googlevideo.com"]',
videoContainer: '#movie_player, .html5-video-player, ytd-player',
rightControls: '.ytp-right-controls, .ytp-chrome-controls .ytp-right-controls',
title: [
'h1.ytd-watch-metadata yt-formatted-string',
'h1.title.ytd-video-primary-info-renderer',
'h1.watch-title-container',
'#title h1',
'ytd-watch-metadata h1',
],
channel: [
'ytd-channel-name yt-formatted-string a',
'#upload-info ytd-channel-name a',
'.ytd-channel-name a',
],
};
// ===== 工具函数 =====
function getVideoTitle() {
for (const selector of SELECTORS.title) {
const el = document.querySelector(selector);
if (el && el.textContent.trim()) {
return sanitizeFilename(el.textContent.trim());
}
}
return 'YouTube_Video';
}
function getChannelName() {
for (const selector of SELECTORS.channel) {
const el = document.querySelector(selector);
if (el && el.textContent.trim()) {
return sanitizeFilename(el.textContent.trim());
}
}
return '';
}
function sanitizeFilename(str) {
return str.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').substring(0, 100);
}
function formatTimestamp(seconds) {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
if (hrs > 0) {
return `${hrs}h${mins.toString().padStart(2, '0')}m${secs.toString().padStart(2, '0')}s`;
}
return `${mins}m${secs.toString().padStart(2, '0')}s`;
}
function formatDate() {
const now = new Date();
return `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getDate().toString().padStart(2,'0')}`;
}
function getCurrentTimeString() {
const now = new Date();
return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}
function getCurrentDateString() {
const now = new Date();
const month = now.getMonth() + 1;
const date = now.getDate();
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
return `${month}月${date}日 ${weekdays[now.getDay()]}`;
}
function getVideoElement() {
return document.querySelector(SELECTORS.video);
}
// ===== 截图核心功能 =====
async function captureScreenshot() {
const video = getVideoElement();
if (!video) {
showNotification('未找到视频元素', 'error');
return;
}
if (video.readyState < 2) {
showNotification('视频尚未加载完成', 'warning');
return;
}
const currentTime = video.currentTime;
const timestamp = formatTimestamp(currentTime);
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (CONFIG.enableWatermark) {
if (CONFIG.watermarkStyle === 'frame') {
try {
await drawFrameWatermark(ctx, canvas, timestamp, getChannelName(), video.videoWidth, video.videoHeight);
} catch (err) {
console.error('外框水印失败,回退到简洁水印:', err);
drawSimpleWatermark(ctx, canvas, timestamp, getChannelName());
}
} else {
drawSimpleWatermark(ctx, canvas, timestamp, getChannelName());
}
}
showFlashEffect();
const title = getVideoTitle();
const extension = CONFIG.screenshotFormat === 'jpeg' ? 'jpg' : CONFIG.screenshotFormat;
const filename = `${title}_${timestamp}_${formatDate()}.${extension}`;
switch (CONFIG.screenshotAction) {
case 'save':
await saveScreenshot(canvas, filename);
break;
case 'copy': {
const copied = await copyScreenshot(canvas);
if (!copied) {
await saveScreenshot(canvas, filename);
showNotification('剪贴板不可用,已自动保存到本地', 'warning');
}
break;
}
case 'both': {
const [saveRes, copyRes] = await Promise.allSettled([
saveScreenshot(canvas, filename),
copyScreenshot(canvas)
]);
if (copyRes.status === 'fulfilled' && copyRes.value === false) {
showNotification('复制失败,已完成本地保存', 'warning');
}
if (saveRes.status === 'rejected') {
throw saveRes.reason;
}
break;
}
case 'preview':
showPreview(canvas, filename);
break;
default:
await saveScreenshot(canvas, filename);
}
}
// 简洁文字水印
function drawSimpleWatermark(ctx, canvas, timestamp, channel) {
const fontSize = Math.max(14, Math.floor(canvas.height / 40));
ctx.font = `bold ${fontSize}px "Segoe UI", "Microsoft YaHei", sans-serif`;
ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
ctx.lineWidth = 2;
const text = channel ? `${channel} · ${timestamp}` : timestamp;
const padding = fontSize;
const textMetrics = ctx.measureText(text);
const textWidth = textMetrics.width;
const textHeight = fontSize;
let x, y;
switch (CONFIG.watermarkPosition) {
case 'top-left':
x = padding;
y = padding + textHeight;
break;
case 'top-right':
x = canvas.width - textWidth - padding;
y = padding + textHeight;
break;
case 'bottom-left':
x = padding;
y = canvas.height - padding;
break;
case 'bottom-right':
default:
x = canvas.width - textWidth - padding;
y = canvas.height - padding;
break;
}
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
}
// 外框水印(相框风格 - 类似小米徕卡/vivo蔡司)
async function drawFrameWatermark(ctx, canvas, videoTime, channel, videoWidth, videoHeight) {
const frameSize = Math.floor(Math.min(canvas.width, canvas.height) * 0.04);
const bottomBarHeight = Math.floor(frameSize * 2.2);
// 创建新画布,带边框
const framedCanvas = document.createElement('canvas');
framedCanvas.width = canvas.width + frameSize * 2;
framedCanvas.height = canvas.height + frameSize + bottomBarHeight;
const fCtx = framedCanvas.getContext('2d');
// 启用高清渲染
fCtx.imageSmoothingEnabled = true;
fCtx.imageSmoothingQuality = 'high';
// 填充白色背景
fCtx.fillStyle = '#ffffff';
fCtx.fillRect(0, 0, framedCanvas.width, framedCanvas.height);
// 绘制原图
fCtx.drawImage(canvas, frameSize, frameSize, canvas.width, canvas.height);
// 底部信息栏
const barY = canvas.height + frameSize;
const barHeight = bottomBarHeight;
const padding = frameSize * 1.5;
// 左侧:绘制 Logo(带卡片边框,避免“空白感”)
const logoSize = Math.floor(barHeight * 0.85);
const logoX = padding;
const logoY = barY + (barHeight - logoSize) / 2;
// 先画一个圆角白底卡片,保证 logo 区域始终可见
const cardPad = Math.max(2, Math.floor(frameSize * 0.12));
const cardX = logoX - cardPad;
const cardY = logoY - cardPad;
const cardSize = logoSize + cardPad * 2;
const cardRadius = Math.floor(cardSize * 0.22);
fCtx.save();
fCtx.fillStyle = '#ffffff';
if (typeof fCtx.roundRect === 'function') {
fCtx.beginPath();
fCtx.roundRect(cardX, cardY, cardSize, cardSize, cardRadius);
fCtx.fill();
} else {
// 兼容兜底:无 roundRect 时使用普通矩形
fCtx.fillRect(cardX, cardY, cardSize, cardSize);
}
fCtx.restore();
try {
const logoImg = await loadLogoImageHD();
if (logoImg) {
fCtx.drawImage(logoImg, logoX, logoY, logoSize, logoSize);
}
} catch (e) {
console.log('Logo 加载失败:', e);
}
// 计算字体大小
const channelFontSize = Math.floor(barHeight * 0.28);
const urlFontSize = Math.floor(barHeight * 0.16);
const timeFontSize = Math.floor(barHeight * 0.40);
// Logo 右侧:信息区域
const textStartX = logoX + logoSize + Math.floor(frameSize * 0.3); // 缩小间距,更靠近 logo
// 启用文字抗锯齿
fCtx.textRendering = 'optimizeLegibility';
// 第一行:频道名称
fCtx.font = `600 ${channelFontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`;
fCtx.fillStyle = '#1d1d1f';
fCtx.textBaseline = 'middle';
const displayChannel = channel || 'YouTube';
fCtx.fillText(displayChannel, textStartX, barY + barHeight * 0.35);
// 第二行:视频 URL
fCtx.font = `400 ${urlFontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`;
fCtx.fillStyle = '#666666';
const currentUrl = window.location.href;
let urlDisplay = 'youtube.com';
if (currentUrl.includes('youtube.com/watch')) {
const urlObj = new URL(currentUrl);
urlDisplay = 'youtube.com/watch?v=' + urlObj.searchParams.get('v');
}
fCtx.fillText(urlDisplay, textStartX, barY + barHeight * 0.65);
// 右侧:视频当前时间
fCtx.font = `200 ${timeFontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`;
fCtx.fillStyle = '#1d1d1f';
fCtx.textAlign = 'right';
fCtx.fillText(videoTime, framedCanvas.width - padding, barY + barHeight / 2);
// 重置文本对齐
fCtx.textAlign = 'left';
// 将带边框的画布绘制回原画布
ctx.canvas.width = framedCanvas.width;
ctx.canvas.height = framedCanvas.height;
ctx.drawImage(framedCanvas, 0, 0);
}
// 加载 Logo 图片(高清版)
function loadLogoImageHD() {
return new Promise((resolve) => {
const candidates = ['icons/icon1024.png', 'icons/icon128.png', 'icons/toolbar128.png'];
let idx = 0;
const tryNext = () => {
if (idx >= candidates.length) {
resolve(null);
return;
}
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve(img);
img.onerror = () => {
idx += 1;
tryNext();
};
img.src = chrome.runtime.getURL(candidates[idx]);
};
tryNext();
});
}
async function saveScreenshot(canvas, filename) {
return new Promise((resolve, reject) => {
const mimeType = `image/${CONFIG.screenshotFormat}`;
const quality = CONFIG.screenshotFormat === 'png' ? undefined : CONFIG.screenshotQuality;
canvas.toBlob(async (blob) => {
if (!blob) {
reject(new Error('生成图片失败'));
return;
}
try {
const url = URL.createObjectURL(blob);
await chrome.runtime.sendMessage({
action: 'download',
url: url,
filename: filename
});
URL.revokeObjectURL(url);
showNotification(`已保存: ${filename}`, 'success');
resolve();
} catch (err) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showNotification(`已保存: ${filename}`, 'success');
resolve();
}
}, mimeType, quality);
});
}
async function copyScreenshot(canvas) {
return new Promise((resolve, reject) => {
canvas.toBlob(async (blob) => {
if (!blob) {
reject(new Error('生成图片失败'));
return;
}
if (!navigator.clipboard || !window.ClipboardItem) {
resolve(false);
return;
}
const writeClipboard = async () => {
if (CONFIG.screenshotFormat === 'png') {
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': blob })
]);
} else {
const pngBlob = await canvasToPngBlob(canvas);
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': pngBlob })
]);
}
};
try {
await writeClipboard();
showNotification('已复制到剪贴板', 'success');
resolve(true);
} catch (err) {
// popup 关闭后的焦点切换可能有延迟,重试一次
try {
await new Promise(r => setTimeout(r, 180));
await writeClipboard();
showNotification('已复制到剪贴板', 'success');
resolve(true);
} catch (err2) {
console.warn('复制失败:', err2);
resolve(false);
}
}
}, 'image/png');
});
}
function canvasToPngBlob(canvas) {
return new Promise((resolve) => {
canvas.toBlob((blob) => resolve(blob), 'image/png');
});
}
// ===== UI 组件 =====
function createScreenshotButton() {
const btn = document.createElement('button');
btn.className = 'tubesnap-btn ytp-button';
btn.title = '截图';
btn.setAttribute('aria-label', '截图');
// 改为位图图标,避免 YouTube 对内联 SVG 的样式覆盖导致“图标不显示”
const icon = document.createElement('img');
icon.className = 'tubesnap-btn-icon';
icon.alt = '';
icon.src = chrome.runtime.getURL('icons/toolbar48.png');
icon.draggable = false;
icon.decoding = 'async';
// 加载失败兜底:退回纯 SVG 相机图标
icon.onerror = () => {
btn.innerHTML = `
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="3" fill="currentColor"/>
<path fill="currentColor" d="M20 6h-2.5l-1.5-2h-7L7.5 6H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h15c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H5V8h15v10z"/>
</svg>
`;
};
btn.appendChild(icon);
btn.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
try {
await captureScreenshot();
} catch (err) {
console.error('截图失败:', err);
showNotification('截图失败: ' + err.message, 'error');
}
});
return btn;
}
function addButtonsToPlayer() {
const controls = document.querySelector(SELECTORS.rightControls);
if (!controls) {
isAppended = false;
return false;
}
if (isAppended && controls.querySelector('.tubesnap-btn')) {
return true;
}
if (!screenshotButton) {
screenshotButton = createScreenshotButton();
}
controls.prepend(screenshotButton);
isAppended = true;
return true;
}
// ===== 特效与反馈 =====
function showFlashEffect() {
const video = getVideoElement();
const rect = video?.getBoundingClientRect?.();
const flash = document.createElement('div');
flash.className = 'tubesnap-flash';
if (rect && rect.width > 0 && rect.height > 0) {
flash.style.cssText = `
position: fixed;
left: ${Math.max(0, rect.left)}px;
top: ${Math.max(0, rect.top)}px;
width: ${rect.width}px;
height: ${rect.height}px;
border-radius: 10px;
box-shadow: inset 0 0 0 2px rgba(255,255,255,0.85), 0 0 0 1px rgba(0,0,0,0.18);
background: radial-gradient(circle at center, rgba(255,255,255,0.22), rgba(255,255,255,0.05) 60%, rgba(255,255,255,0));
opacity: 0;
transform: scale(1.01);
pointer-events: none;
z-index: 999999;
transition: opacity 120ms ease-out, transform 180ms ease-out;
`;
} else {
flash.style.cssText = `
position: fixed;
inset: 0;
background: rgba(255, 255, 255, 0.16);
opacity: 0;
pointer-events: none;
z-index: 999999;
transition: opacity 120ms ease-out;
`;
}
document.body.appendChild(flash);
requestAnimationFrame(() => {
flash.style.opacity = '1';
flash.style.transform = 'scale(1)';
setTimeout(() => {
flash.style.opacity = '0';
setTimeout(() => flash.remove(), 180);
}, 80);
});
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `tubesnap-notify tubesnap-notify-${type}`;
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 80px;
right: 20px;
padding: 12px 20px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
z-index: 10000;
animation: tubesnap-slide-in 0.3s ease-out;
backdrop-filter: blur(10px);
${type === 'success' ? 'background: rgba(76, 175, 80, 0.9); color: white;' : ''}
${type === 'error' ? 'background: rgba(244, 67, 54, 0.9); color: white;' : ''}
${type === 'warning' ? 'background: rgba(255, 152, 0, 0.9); color: white;' : ''}
${type === 'info' ? 'background: rgba(33, 150, 243, 0.9); color: white;' : ''}
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'tubesnap-slide-out 0.3s ease-in forwards';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
function showPreview(canvas, filename) {
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const previewWindow = window.open('', '_blank', 'width=1200,height=800');
if (!previewWindow) {
showNotification('弹窗被阻止,请允许弹窗以使用预览功能', 'warning');
return;
}
previewWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>截图预览 - ${filename}</title>
<style>
body { margin: 0; padding: 20px; background: #1a1a1a; color: #fff; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }
.header { margin-bottom: 20px; text-align: center; }
.filename { font-size: 14px; color: #aaa; margin-top: 8px; }
.image-container { max-width: 100%; background: #000; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }
img { max-width: 100%; max-height: 70vh; display: block; }
.actions { margin-top: 20px; display: flex; gap: 12px; }
button { padding: 10px 24px; border: none; border-radius: 6px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.2s; }
.btn-save { background: #4CAF50; color: white; }
.btn-save:hover { background: #45a049; }
.btn-copy { background: #2196F3; color: white; }
.btn-copy:hover { background: #1e88e5; }
.btn-close { background: #424242; color: white; }
.btn-close:hover { background: #616161; }
</style>
</head>
<body>
<div class="header">
<h2>截图预览</h2>
<div class="filename">${filename}</div>
</div>
<div class="image-container">
<img src="${url}" alt="截图">
</div>
<div class="actions">
<button class="btn-save" onclick="download()">保存到本地</button>
<button class="btn-copy" onclick="copy()">复制到剪贴板</button>
<button class="btn-close" onclick="window.close()">关闭</button>
</div>
<script>
function download() {
const a = document.createElement('a');
a.href = '${url}';
a.download = '${filename}';
a.click();
}
async function copy() {
try {
const response = await fetch('${url}');
const blob = await response.blob();
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
alert('已复制到剪贴板');
} catch (e) {
alert('复制失败: ' + e.message);
}
}
</script>
</body>
</html>
`);
}, 'image/png');
}
// ===== DOM 观察器 =====
const observer = new MutationObserver(() => {
if (!isAppended) {
addButtonsToPlayer();
}
});
// ===== 初始化 =====
function init() {
chrome.storage.sync.get([
'screenshotFormat',
'screenshotQuality',
'screenshotAction',
'enableWatermark',
'watermarkPosition',
'watermarkStyle'
], (result) => {
Object.assign(CONFIG, result);
addButtonsToPlayer();
});
chrome.storage.onChanged.addListener((changes) => {
for (let key in changes) {
if (CONFIG.hasOwnProperty(key)) {
CONFIG[key] = changes[key].newValue;
}
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'take-screenshot') {
captureScreenshot();
sendResponse({ success: true });
}
return true;
});
observer.observe(document.body, {
childList: true,
subtree: true
});
setInterval(() => {
if (!document.querySelector('.tubesnap-btn')) {
isAppended = false;
addButtonsToPlayer();
}
}, 2000);
}
// 注入动画样式
const style = document.createElement('style');
style.textContent = `
@keyframes tubesnap-slide-in {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes tubesnap-slide-out {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
}
`;
document.head.appendChild(style);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}