customer-chat-sdk 1.0.28 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { destroyContext, createContext, domToPng } from 'modern-screenshot';
2
+ import snapdom from '@zumer/snapdom';
2
3
 
3
4
  // 直接使用base64字符串,避免打包后路径问题
4
5
  const iconImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAArKSURBVHgB7Z1NbFTXFcf/93mwaGyEabLoIgFTqWRFMZUitSoIu80ial01SFWrKgsGKXYpWdRtFilRK4xUgbKICosmCKIySKCo2UAE6i61XVroDuOoi2YT02RZVFNwQTAzN+e8N88ej9+8j5n3ce5wf5JhPvyY4f3f/9xzz73vXoUeYKish6oljCiFYQ2MaAebVR3D/Jzf1xpDUPTTggIW6feXoOlH0Q9wS9exRK/Pl6qYX6qoJRiOgoEMvqpHWUjlYJ9iQeEJmTb07y6y2CT6HP99/z01C8MwQmB26OMSyuTIH9LTkSA35oLn9FmKCB/WHmP2YUUtQjhiBV4jqsIoJKJJbOC8ZLHFCczhl75UWXvCFuPUDiBXV5TGeWlhXIzALCx9m6Ni3RqfeRL71PJZVYEAChfYdayDc1klSkXBCRr9caxooQsTuIccG4qbiddxsKjQnbvAlDwNVzfgXK8L2wq30ZSMHcs7GctV4IFX9ZTyXGtM8pQq2i2qnCQ3H0NO5CLwk+radnDYrj3CWB5udpAx7FoS96YVdxVy1XCJzgmfG2RMZg5268P9FI6BzP8TRlN3Q/YvkRGZCOyG5H5cApcVLZFkGbJTF3igrEccErfX+rVZk5XIqbbBmyb1y2oDZqy4yfHbZT6HSJHUHDwwqQ/QP1aBpWvIIOXlM+o8UiAVga246ZOWyF0LbMXNjjRE7kpgbi/oS1yCJTNIoP33zqjL6JCOBW5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d9ajAgbKfASVUa0DdXy0DjVWrUKIvbyKzbhkkNUYtVM7LsLbagWAodmB2Nxfz22wDZUy0BTnzdOaPZJdH8whYWTHPthKQY698vvkQYJSLwEGq9BXO13N68UvztpL5Gk3W0m8R3+PGZccrCfroxFWHKBxU3S7jbT8SKGAxN6hA6ekTaXuuegpKrah91J2t1mOl6jY/msmlfKDkhkDZ/jTsVlulqE5d4ZdVlpK3JWUMZ8kM8xuiCVdWY3TegydaHOwZIaLC5FyQq6JLWFhK3I6ZGWuExq62Tdoy9EV8t+W+3qAjp3fA7TEpdJfSnwoUN6uFbHjJ3ukwzuCtEfLG6qN+mkvtIdlzT7qM9m+8mJmOd+btriMpksZeiK/Ai7bVkzBnSOSk9hrJuuUBiZ79YwMKmnqCt11BZEWqD2lgcOktaWk5LLdhy2XV7HXNVBOSvXNpPrfiuDk3qartxfPLFuzsm1zeS+oU7DzdPk5sLvf8qZ3FzbTGE7JvG28qqOc09A2J6jVHbanaFaAAVvieVVwOhbHO01oblfqxwcLEpYn8IF9mmUOqfooYjdyLugUMe2IkZgn0boLhvVRnPy5OAyDe2dlyKsjziBfdxkrIZRcnWZnu6DTOZ0HZc3DKKydFKJrMGLFbiZFbGBl8FiF9XN4oEUhVvSRW3GCIFb4TDOW9NTSByln11ZJWi8zDKvxMsLe/J6ntLCbxyMFLiVoSk9VH2IEVd03rKedzX3XD7EO3AG7gvlDc3ddR8qLLpZr6LX6iRoHxZLGzFvgkOj+ALBlx6CtCZy6AAAAABJRU5ErkJggg==';
@@ -922,28 +923,6 @@ class IframeManager {
922
923
  }
923
924
 
924
925
  // @ts-ignore - modern-screenshot may not have type definitions
925
- // Worker URL 将在创建上下文时动态获取
926
- // 在 Vite 环境中可以使用: import workerUrl from 'modern-screenshot/worker?url'
927
- // 在 Rollup 中,modern-screenshot 会自动处理 worker URL
928
- let workerUrl = undefined;
929
- // 尝试动态获取 worker URL(仅在支持的环境中)
930
- async function getWorkerUrl() {
931
- if (workerUrl) {
932
- return workerUrl;
933
- }
934
- try {
935
- // 尝试使用 Vite 的 ?url 语法(仅在 Vite 环境中有效)
936
- // @ts-ignore - Vite 特有的 ?url 语法
937
- const workerModule = await import('modern-screenshot/worker?url');
938
- workerUrl = workerModule.default || workerModule;
939
- return workerUrl;
940
- }
941
- catch {
942
- // Rollup 或其他构建工具不支持 ?url 语法
943
- // modern-screenshot 会自动处理 worker URL,返回 undefined 即可
944
- return undefined;
945
- }
946
- }
947
926
  /**
948
927
  * 截图管理器
949
928
  * 负责页面截图、压缩和上传功能
@@ -973,8 +952,16 @@ class ScreenshotManager {
973
952
  this.dynamicInterval = null;
974
953
  // 过期定时器
975
954
  this.expirationTimer = null;
976
- // 图片代理缓存
955
+ // 图片代理缓存(带过期时间)
977
956
  this.imageProxyCache = new Map();
957
+ // IndexedDB 缓存(持久化)
958
+ this.indexedDBCache = null;
959
+ this.indexedDBReady = false;
960
+ // Intersection Observer(用于高效检测可见性)
961
+ this.intersectionObserver = null;
962
+ this.visibleElementsCache = new Set();
963
+ // 预连接状态
964
+ this.preconnected = false;
978
965
  // 全局错误处理器
979
966
  this.globalErrorHandler = null;
980
967
  this.globalRejectionHandler = null;
@@ -996,10 +983,37 @@ class ScreenshotManager {
996
983
  maxRetries: options.maxRetries ?? 2,
997
984
  preloadImages: options.preloadImages ?? false, // 默认不预加载,按需加载
998
985
  maxConcurrentDownloads: options.maxConcurrentDownloads ?? 10, // 增加并发数
999
- onlyVisibleImages: options.onlyVisibleImages ?? true // 默认只处理可视区域
986
+ onlyVisibleImages: options.onlyVisibleImages ?? true, // 默认只处理可视区域
987
+ imageCacheTTL: options.imageCacheTTL ?? 600000, // 默认10分钟(600000ms)
988
+ useIndexedDB: options.useIndexedDB ?? true, // 默认启用 IndexedDB 持久化缓存
989
+ usePreconnect: options.usePreconnect ?? true, // 默认预连接代理服务器
990
+ imageLoadTimeout: options.imageLoadTimeout ?? 5000, // 默认5秒超时
991
+ useIntersectionObserver: options.useIntersectionObserver ?? true, // 默认使用 Intersection Observer
992
+ fetchPriority: options.fetchPriority ?? 'high', // 默认高优先级
993
+ maxCacheSize: options.maxCacheSize ?? 50, // 默认最大50MB
994
+ maxCacheAge: options.maxCacheAge ?? 86400000 // 默认24小时(86400000ms)
1000
995
  };
1001
996
  this.setupMessageListener();
1002
997
  this.setupVisibilityChangeListener();
998
+ // 启动缓存清理定时器
999
+ this.startCacheCleanup();
1000
+ // 预连接代理服务器(如果启用)
1001
+ if (this.options.usePreconnect && this.options.proxyUrl) {
1002
+ this.preconnectProxy();
1003
+ }
1004
+ // 初始化 Intersection Observer(如果启用)
1005
+ if (this.options.useIntersectionObserver && this.options.onlyVisibleImages) {
1006
+ this.initIntersectionObserver();
1007
+ }
1008
+ // 初始化 IndexedDB(如果启用)
1009
+ if (this.options.useIndexedDB) {
1010
+ this.initIndexedDB().catch(() => {
1011
+ // IndexedDB 初始化失败,回退到内存缓存
1012
+ if (!this.options.silentMode) {
1013
+ console.warn('📸 IndexedDB 初始化失败,使用内存缓存');
1014
+ }
1015
+ });
1016
+ }
1003
1017
  }
1004
1018
  /**
1005
1019
  * 设置目标元素
@@ -1303,21 +1317,41 @@ class ScreenshotManager {
1303
1317
  this.waitForStylesAndFonts(),
1304
1318
  this.waitForFonts()
1305
1319
  ]);
1306
- // 选择截图引擎(仅支持 modern-screenshot)
1307
- const selectedEngine = 'modern-screenshot';
1320
+ // 选择截图引擎
1321
+ const selectedEngine = this.options.engine || 'modern-screenshot';
1308
1322
  if (!this.options.silentMode) {
1309
- console.log(`📸 使用截图引擎: ${selectedEngine} (Worker 模式)`);
1323
+ console.log(`📸 使用截图引擎: ${selectedEngine}`);
1310
1324
  }
1311
- // 优化:如果启用预加载,才预处理图片;否则让 modern-screenshot 按需加载
1312
- if (this.options.preloadImages && this.options.enableCORS) {
1325
+ // 优化:如果启用预加载,才预处理图片;否则让引擎按需加载
1326
+ if (this.options.preloadImages && this.options.enableCORS && selectedEngine === 'modern-screenshot') {
1327
+ // 清理过期缓存
1328
+ this.cleanExpiredCache();
1329
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
1330
+ if (this.options.useIndexedDB) {
1331
+ await this.cleanIndexedDBCache();
1332
+ }
1313
1333
  await this.preprocessNetworkImages(this.targetElement);
1314
1334
  await this.waitForImagesToLoad(this.targetElement);
1315
1335
  }
1336
+ else {
1337
+ // 即使不预加载,也清理一下过期缓存
1338
+ this.cleanExpiredCache();
1339
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
1340
+ if (this.options.useIndexedDB) {
1341
+ await this.cleanIndexedDBCache();
1342
+ }
1343
+ }
1316
1344
  let dataUrl;
1317
1345
  // 等待一小段时间,确保 DOM 更新完成(减少等待时间)
1318
1346
  await new Promise(resolve => setTimeout(resolve, 50));
1319
- // 使用 modern-screenshot 截图(启用 Worker)
1320
- dataUrl = await this.takeScreenshotWithModernScreenshot(this.targetElement);
1347
+ // 根据选择的引擎进行截图
1348
+ if (selectedEngine === 'snapdom') {
1349
+ dataUrl = await this.takeScreenshotWithSnapdom(this.targetElement);
1350
+ }
1351
+ else {
1352
+ // 默认使用 modern-screenshot
1353
+ dataUrl = await this.takeScreenshotWithModernScreenshot(this.targetElement);
1354
+ }
1321
1355
  const timestamp = Date.now();
1322
1356
  // 更新状态
1323
1357
  this.screenshotCount++;
@@ -1381,6 +1415,94 @@ class ScreenshotManager {
1381
1415
  this.removeGlobalErrorHandlers();
1382
1416
  }
1383
1417
  }
1418
+ /**
1419
+ * 使用 snapdom 截图
1420
+ * 参考: https://snapdom.dev/#cors
1421
+ * 参考: https://github.com/zumerlab/snapdom/blob/main/README_CN.md
1422
+ *
1423
+ * 注意:snapdom 内部使用 worker 进行截图处理,会在后台线程执行,不会阻塞主线程
1424
+ */
1425
+ async takeScreenshotWithSnapdom(element) {
1426
+ if (!this.options.silentMode) {
1427
+ console.log('📸 使用 snapdom 引擎截图...');
1428
+ }
1429
+ try {
1430
+ // 检查元素是否存在和可见
1431
+ const rect = element.getBoundingClientRect();
1432
+ if (rect.width === 0 || rect.height === 0) {
1433
+ throw new Error('元素尺寸为 0,无法截图');
1434
+ }
1435
+ // 构建 snapdom 选项
1436
+ const options = {};
1437
+ // 如果配置了代理服务器,使用 useProxy 选项处理跨域图片和字体
1438
+ // 参考: https://github.com/zumerlab/snapdom/blob/main/README_CN.md#跨域图片和字体-useproxy
1439
+ if (this.options.proxyUrl && this.options.proxyUrl.trim() !== '') {
1440
+ // snapdom 的 useProxy 是字符串格式的代理 URL 模板
1441
+ // 它会自动将跨域图片 URL 附加到代理 URL 后面
1442
+ let proxyUrl = this.options.proxyUrl.trim();
1443
+ // 确保代理 URL 以 ?url= 结尾(snapdom 会自动附加图片 URL)
1444
+ if (!proxyUrl.includes('?url=')) {
1445
+ proxyUrl = proxyUrl.endsWith('?') ? proxyUrl + 'url=' : proxyUrl + '?url=';
1446
+ }
1447
+ options.useProxy = proxyUrl;
1448
+ if (!this.options.silentMode) {
1449
+ console.log(`📸 使用代理服务器处理跨域图片: ${proxyUrl}`);
1450
+ }
1451
+ }
1452
+ else {
1453
+ if (!this.options.silentMode) {
1454
+ console.log('📸 不使用代理,直接截图(可能遇到 CORS 问题)');
1455
+ }
1456
+ }
1457
+ // 根据输出格式选择对应的快捷方法
1458
+ // 参考: https://github.com/zumerlab/snapdom/blob/main/README_CN.md#快捷方法
1459
+ const outputFormat = this.options.outputFormat || 'png';
1460
+ let img;
1461
+ switch (outputFormat) {
1462
+ case 'jpeg':
1463
+ // 使用 toJpg 快捷方法(snapdom 使用 jpg 作为方法名)
1464
+ img = await snapdom.toJpg(element, options);
1465
+ break;
1466
+ case 'webp':
1467
+ // 使用 toWebp 快捷方法
1468
+ img = await snapdom.toWebp(element, options);
1469
+ break;
1470
+ case 'png':
1471
+ default:
1472
+ // 使用 toPng 快捷方法(默认)
1473
+ img = await snapdom.toPng(element, options);
1474
+ break;
1475
+ }
1476
+ // 获取 base64 数据(HTMLImageElement 的 src 属性包含 data URL)
1477
+ const dataUrl = img.src;
1478
+ // 验证 base64 是否有效
1479
+ if (!dataUrl || dataUrl.length < 100) {
1480
+ throw new Error('生成的 base64 数据无效或过短');
1481
+ }
1482
+ if (!this.options.silentMode) {
1483
+ console.log(`📸 snapdom 截图成功!格式: ${outputFormat}, 尺寸: ${img.width}x${img.height}`);
1484
+ }
1485
+ return dataUrl;
1486
+ }
1487
+ catch (error) {
1488
+ const errorMessage = error instanceof Error ? error.message : String(error);
1489
+ const errorName = error instanceof Error ? error.name : 'Unknown';
1490
+ // 针对不同类型的错误给出具体提示
1491
+ if (errorName === 'EncodingError' || errorMessage.includes('cannot be decoded')) {
1492
+ if (!this.options.silentMode) {
1493
+ console.warn('📸 ⚠️ 图片解码失败 - 这通常是因为跨域图片无法访问');
1494
+ console.warn('📸 💡 解决方案:配置 proxyUrl 选项');
1495
+ console.warn('📸 📖 参考: https://snapdom.dev/#cors');
1496
+ }
1497
+ }
1498
+ else if (errorMessage.includes('CORS') || errorMessage.includes('cross-origin')) {
1499
+ if (!this.options.silentMode) {
1500
+ console.warn('📸 ⚠️ 检测到 CORS 错误,建议配置 proxyUrl 选项');
1501
+ }
1502
+ }
1503
+ throw error;
1504
+ }
1505
+ }
1384
1506
  /**
1385
1507
  * 使用 modern-screenshot 截图(启用 Worker)
1386
1508
  */
@@ -1412,9 +1534,25 @@ class ScreenshotManager {
1412
1534
  }
1413
1535
  // 如果配置了代理服务器,使用代理处理跨域图片
1414
1536
  if (this.options.proxyUrl && this.options.proxyUrl.trim() !== '') {
1415
- // 检查缓存
1416
- if (this.imageProxyCache.has(url)) {
1417
- return this.imageProxyCache.get(url);
1537
+ // 检查内存缓存(优先使用缓存,带过期时间检查)
1538
+ const cachedDataUrl = this.getCachedImage(url);
1539
+ if (cachedDataUrl) {
1540
+ if (!this.options.silentMode) {
1541
+ console.log(`📸 ✅ 使用内存缓存图片: ${url.substring(0, 50)}...`);
1542
+ }
1543
+ return cachedDataUrl;
1544
+ }
1545
+ // 检查 IndexedDB 缓存(如果启用)
1546
+ if (this.options.useIndexedDB) {
1547
+ const indexedDBCache = await this.getIndexedDBCache(url);
1548
+ if (indexedDBCache) {
1549
+ // 同步到内存缓存
1550
+ this.setCachedImage(url, indexedDBCache);
1551
+ if (!this.options.silentMode) {
1552
+ console.log(`📸 ✅ 使用 IndexedDB 缓存图片: ${url.substring(0, 50)}...`);
1553
+ }
1554
+ return indexedDBCache;
1555
+ }
1418
1556
  }
1419
1557
  try {
1420
1558
  // 构建代理请求参数
@@ -1428,11 +1566,11 @@ class ScreenshotManager {
1428
1566
  let baseUrl = this.options.proxyUrl;
1429
1567
  baseUrl = baseUrl.replace(/[?&]$/, '');
1430
1568
  const proxyUrl = `${baseUrl}?${params.toString()}`;
1431
- // 请求代理服务器(优化:添加超时控制)
1569
+ // 请求代理服务器(优化:添加超时控制和优先级)
1432
1570
  const controller = new AbortController();
1433
- const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
1571
+ const timeoutId = setTimeout(() => controller.abort(), this.options.imageLoadTimeout);
1434
1572
  try {
1435
- const response = await fetch(proxyUrl, {
1573
+ const fetchOptions = {
1436
1574
  method: 'GET',
1437
1575
  mode: 'cors',
1438
1576
  credentials: 'omit',
@@ -1441,15 +1579,24 @@ class ScreenshotManager {
1441
1579
  },
1442
1580
  cache: 'no-cache',
1443
1581
  signal: controller.signal
1444
- });
1582
+ };
1583
+ // 添加 fetch priority(如果支持)
1584
+ if ('priority' in fetchOptions) {
1585
+ fetchOptions.priority = this.options.fetchPriority;
1586
+ }
1587
+ const response = await fetch(proxyUrl, fetchOptions);
1445
1588
  clearTimeout(timeoutId);
1446
1589
  if (!response.ok) {
1447
1590
  throw new Error(`代理请求失败: ${response.status}`);
1448
1591
  }
1449
1592
  const blob = await response.blob();
1450
1593
  const dataUrl = await this.blobToDataUrl(blob);
1451
- // 缓存结果
1452
- this.imageProxyCache.set(url, dataUrl);
1594
+ // 缓存结果(带时间戳,10分钟有效)
1595
+ this.setCachedImage(url, dataUrl);
1596
+ // 如果启用 IndexedDB,也保存到 IndexedDB
1597
+ if (this.options.useIndexedDB) {
1598
+ await this.setIndexedDBCache(url, dataUrl);
1599
+ }
1453
1600
  return dataUrl;
1454
1601
  }
1455
1602
  catch (fetchError) {
@@ -1496,11 +1643,7 @@ class ScreenshotManager {
1496
1643
  if (this.options.scale !== 1) {
1497
1644
  contextOptions.scale = isMobile ? 0.8 : this.options.scale;
1498
1645
  }
1499
- // 尝试设置 workerUrl(如果可用)
1500
- const resolvedWorkerUrl = await getWorkerUrl();
1501
- if (resolvedWorkerUrl) {
1502
- contextOptions.workerUrl = resolvedWorkerUrl;
1503
- }
1646
+ // modern-screenshot 会自动处理 worker URL,不需要手动设置
1504
1647
  // 创建 Worker 上下文
1505
1648
  this.screenshotContext = await createContext(element, contextOptions);
1506
1649
  }
@@ -1564,23 +1707,336 @@ class ScreenshotManager {
1564
1707
  }
1565
1708
  }
1566
1709
  /**
1567
- * 检查元素是否在可视区域内
1710
+ * 预连接代理服务器(优化网络性能)
1711
+ */
1712
+ preconnectProxy() {
1713
+ if (this.preconnected || !this.options.proxyUrl) {
1714
+ return;
1715
+ }
1716
+ try {
1717
+ const proxyOrigin = new URL(this.options.proxyUrl).origin;
1718
+ const link = document.createElement('link');
1719
+ link.rel = 'preconnect';
1720
+ link.href = proxyOrigin;
1721
+ link.crossOrigin = 'anonymous';
1722
+ document.head.appendChild(link);
1723
+ this.preconnected = true;
1724
+ if (!this.options.silentMode) {
1725
+ console.log(`📸 ✅ 已预连接代理服务器: ${proxyOrigin}`);
1726
+ }
1727
+ }
1728
+ catch (e) {
1729
+ // 预连接失败,不影响功能
1730
+ }
1731
+ }
1732
+ /**
1733
+ * 初始化 Intersection Observer(优化可见性检测)
1734
+ */
1735
+ initIntersectionObserver() {
1736
+ if (!('IntersectionObserver' in window)) {
1737
+ return;
1738
+ }
1739
+ this.intersectionObserver = new IntersectionObserver((entries) => {
1740
+ entries.forEach((entry) => {
1741
+ if (entry.isIntersecting) {
1742
+ this.visibleElementsCache.add(entry.target);
1743
+ }
1744
+ else {
1745
+ this.visibleElementsCache.delete(entry.target);
1746
+ }
1747
+ });
1748
+ }, {
1749
+ root: null,
1750
+ rootMargin: '50px', // 提前50px开始加载
1751
+ threshold: 0.01
1752
+ });
1753
+ }
1754
+ /**
1755
+ * 初始化 IndexedDB(持久化缓存)
1756
+ */
1757
+ async initIndexedDB() {
1758
+ return new Promise((resolve, reject) => {
1759
+ const request = indexedDB.open('screenshot-cache', 1);
1760
+ request.onerror = () => reject(request.error);
1761
+ request.onsuccess = () => {
1762
+ this.indexedDBCache = request.result;
1763
+ this.indexedDBReady = true;
1764
+ // 初始化后立即清理过期和超大小的缓存
1765
+ this.cleanIndexedDBCache().catch(() => {
1766
+ // 清理失败不影响功能
1767
+ });
1768
+ resolve();
1769
+ };
1770
+ request.onupgradeneeded = (event) => {
1771
+ const db = event.target.result;
1772
+ if (!db.objectStoreNames.contains('images')) {
1773
+ const store = db.createObjectStore('images', { keyPath: 'url' });
1774
+ // 创建索引用于按时间排序
1775
+ store.createIndex('timestamp', 'timestamp', { unique: false });
1776
+ }
1777
+ };
1778
+ });
1779
+ }
1780
+ /**
1781
+ * 从 IndexedDB 获取缓存
1782
+ */
1783
+ async getIndexedDBCache(url) {
1784
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1785
+ return null;
1786
+ }
1787
+ try {
1788
+ const transaction = this.indexedDBCache.transaction(['images'], 'readonly');
1789
+ const store = transaction.objectStore('images');
1790
+ const request = store.get(url);
1791
+ return new Promise((resolve) => {
1792
+ request.onsuccess = () => {
1793
+ const result = request.result;
1794
+ if (result) {
1795
+ const now = Date.now();
1796
+ const age = now - result.timestamp;
1797
+ // 检查是否超过最大缓存时间
1798
+ if (age > this.options.maxCacheAge) {
1799
+ // 缓存过期,删除
1800
+ this.deleteIndexedDBCache(url);
1801
+ resolve(null);
1802
+ return;
1803
+ }
1804
+ // 返回缓存数据(即使超过 imageCacheTTL,只要未超过 maxCacheAge 仍可使用)
1805
+ resolve(result.dataUrl);
1806
+ }
1807
+ else {
1808
+ resolve(null);
1809
+ }
1810
+ };
1811
+ request.onerror = () => resolve(null);
1812
+ });
1813
+ }
1814
+ catch {
1815
+ return null;
1816
+ }
1817
+ }
1818
+ /**
1819
+ * 设置 IndexedDB 缓存(带大小和时间控制)
1820
+ */
1821
+ async setIndexedDBCache(url, dataUrl) {
1822
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1823
+ return;
1824
+ }
1825
+ try {
1826
+ // 计算当前缓存大小
1827
+ const currentSize = await this.getIndexedDBCacheSize();
1828
+ const newItemSize = this.estimateDataUrlSize(dataUrl);
1829
+ const maxSizeBytes = (this.options.maxCacheSize || 50) * 1024 * 1024; // 转换为字节
1830
+ // 如果添加新项后超过限制,清理最旧的数据
1831
+ if (currentSize + newItemSize > maxSizeBytes) {
1832
+ await this.cleanIndexedDBCacheBySize(maxSizeBytes - newItemSize);
1833
+ }
1834
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1835
+ const store = transaction.objectStore('images');
1836
+ store.put({ url, dataUrl, timestamp: Date.now() });
1837
+ }
1838
+ catch {
1839
+ // IndexedDB 写入失败,忽略
1840
+ }
1841
+ }
1842
+ /**
1843
+ * 估算 data URL 的大小(字节)
1844
+ */
1845
+ estimateDataUrlSize(dataUrl) {
1846
+ // Base64 编码后的大小约为原始大小的 4/3
1847
+ // data:image/xxx;base64, 前缀约 22-30 字节
1848
+ const base64Data = dataUrl.split(',')[1] || '';
1849
+ return Math.ceil(base64Data.length * 0.75) + 30;
1850
+ }
1851
+ /**
1852
+ * 获取 IndexedDB 当前缓存大小(字节)
1853
+ */
1854
+ async getIndexedDBCacheSize() {
1855
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1856
+ return 0;
1857
+ }
1858
+ try {
1859
+ const transaction = this.indexedDBCache.transaction(['images'], 'readonly');
1860
+ const store = transaction.objectStore('images');
1861
+ const request = store.getAll();
1862
+ return new Promise((resolve) => {
1863
+ request.onsuccess = () => {
1864
+ const items = request.result || [];
1865
+ let totalSize = 0;
1866
+ items.forEach((item) => {
1867
+ totalSize += this.estimateDataUrlSize(item.dataUrl);
1868
+ });
1869
+ resolve(totalSize);
1870
+ };
1871
+ request.onerror = () => resolve(0);
1872
+ });
1873
+ }
1874
+ catch {
1875
+ return 0;
1876
+ }
1877
+ }
1878
+ /**
1879
+ * 清理 IndexedDB 缓存(按时间和大小)
1880
+ */
1881
+ async cleanIndexedDBCache() {
1882
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1883
+ return;
1884
+ }
1885
+ try {
1886
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1887
+ const store = transaction.objectStore('images');
1888
+ const index = store.index('timestamp');
1889
+ const request = index.getAll();
1890
+ return new Promise((resolve) => {
1891
+ request.onsuccess = () => {
1892
+ const items = request.result || [];
1893
+ const now = Date.now();
1894
+ const expiredUrls = [];
1895
+ let currentSize = 0;
1896
+ const maxSizeBytes = (this.options.maxCacheSize || 50) * 1024 * 1024;
1897
+ // 按时间排序(最旧的在前)
1898
+ items.sort((a, b) => a.timestamp - b.timestamp);
1899
+ // 清理过期数据
1900
+ items.forEach((item) => {
1901
+ const age = now - item.timestamp;
1902
+ if (age > this.options.maxCacheAge) {
1903
+ expiredUrls.push(item.url);
1904
+ }
1905
+ else {
1906
+ currentSize += this.estimateDataUrlSize(item.dataUrl);
1907
+ }
1908
+ });
1909
+ // 如果仍然超过大小限制,删除最旧的数据
1910
+ const urlsToDelete = [...expiredUrls];
1911
+ if (currentSize > maxSizeBytes) {
1912
+ for (const item of items) {
1913
+ if (expiredUrls.includes(item.url))
1914
+ continue;
1915
+ currentSize -= this.estimateDataUrlSize(item.dataUrl);
1916
+ urlsToDelete.push(item.url);
1917
+ if (currentSize <= maxSizeBytes) {
1918
+ break;
1919
+ }
1920
+ }
1921
+ }
1922
+ // 删除过期和超大小的数据
1923
+ urlsToDelete.forEach((url) => {
1924
+ store.delete(url);
1925
+ });
1926
+ if (urlsToDelete.length > 0 && !this.options.silentMode) {
1927
+ console.log(`📸 IndexedDB 清理了 ${urlsToDelete.length} 个缓存项(过期或超大小)`);
1928
+ }
1929
+ resolve();
1930
+ };
1931
+ request.onerror = () => resolve();
1932
+ });
1933
+ }
1934
+ catch {
1935
+ // 清理失败,忽略
1936
+ }
1937
+ }
1938
+ /**
1939
+ * 按大小清理 IndexedDB 缓存
1940
+ */
1941
+ async cleanIndexedDBCacheBySize(targetSize) {
1942
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1943
+ return;
1944
+ }
1945
+ try {
1946
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1947
+ const store = transaction.objectStore('images');
1948
+ const index = store.index('timestamp');
1949
+ const request = index.getAll();
1950
+ return new Promise((resolve) => {
1951
+ request.onsuccess = () => {
1952
+ const items = request.result || [];
1953
+ // 按时间排序(最旧的在前)
1954
+ items.sort((a, b) => a.timestamp - b.timestamp);
1955
+ let currentSize = 0;
1956
+ const urlsToDelete = [];
1957
+ // 计算当前大小
1958
+ items.forEach((item) => {
1959
+ currentSize += this.estimateDataUrlSize(item.dataUrl);
1960
+ });
1961
+ // 如果超过目标大小,删除最旧的数据
1962
+ if (currentSize > targetSize) {
1963
+ for (const item of items) {
1964
+ if (currentSize <= targetSize) {
1965
+ break;
1966
+ }
1967
+ currentSize -= this.estimateDataUrlSize(item.dataUrl);
1968
+ urlsToDelete.push(item.url);
1969
+ }
1970
+ }
1971
+ // 删除数据
1972
+ urlsToDelete.forEach((url) => {
1973
+ store.delete(url);
1974
+ });
1975
+ if (urlsToDelete.length > 0 && !this.options.silentMode) {
1976
+ console.log(`📸 IndexedDB 清理了 ${urlsToDelete.length} 个缓存项(超过大小限制)`);
1977
+ }
1978
+ resolve();
1979
+ };
1980
+ request.onerror = () => resolve();
1981
+ });
1982
+ }
1983
+ catch {
1984
+ // 清理失败,忽略
1985
+ }
1986
+ }
1987
+ /**
1988
+ * 删除 IndexedDB 缓存
1989
+ */
1990
+ async deleteIndexedDBCache(url) {
1991
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1992
+ return;
1993
+ }
1994
+ try {
1995
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1996
+ const store = transaction.objectStore('images');
1997
+ store.delete(url);
1998
+ }
1999
+ catch {
2000
+ // 忽略错误
2001
+ }
2002
+ }
2003
+ /**
2004
+ * 检查元素是否在可视区域内(优化:使用 Intersection Observer 或 getBoundingClientRect)
1568
2005
  */
1569
2006
  isElementVisible(element, container) {
1570
2007
  if (!this.options.onlyVisibleImages) {
1571
2008
  return true; // 如果禁用可视区域检测,返回 true
1572
2009
  }
2010
+ // 如果使用 Intersection Observer 且元素已在缓存中,直接返回
2011
+ if (this.options.useIntersectionObserver && this.intersectionObserver) {
2012
+ if (this.visibleElementsCache.has(element)) {
2013
+ return true;
2014
+ }
2015
+ // 观察元素(如果还没有观察)
2016
+ this.intersectionObserver.observe(element);
2017
+ }
2018
+ // 回退到 getBoundingClientRect
1573
2019
  try {
1574
2020
  const rect = element.getBoundingClientRect();
1575
2021
  const containerRect = container.getBoundingClientRect();
1576
2022
  // 检查元素是否与容器有交集(考虑滚动位置)
1577
- return !(rect.bottom < containerRect.top ||
2023
+ const isIntersecting = !(rect.bottom < containerRect.top ||
1578
2024
  rect.top > containerRect.bottom ||
1579
2025
  rect.right < containerRect.left ||
1580
2026
  rect.left > containerRect.right) && (rect.width > 0 && rect.height > 0 && // 元素有尺寸
1581
2027
  window.getComputedStyle(element).display !== 'none' && // 元素可见
1582
2028
  window.getComputedStyle(element).visibility !== 'hidden' &&
1583
2029
  window.getComputedStyle(element).opacity !== '0');
2030
+ // 更新 Intersection Observer 缓存
2031
+ if (this.options.useIntersectionObserver && this.intersectionObserver) {
2032
+ if (isIntersecting) {
2033
+ this.visibleElementsCache.add(element);
2034
+ }
2035
+ else {
2036
+ this.visibleElementsCache.delete(element);
2037
+ }
2038
+ }
2039
+ return isIntersecting;
1584
2040
  }
1585
2041
  catch {
1586
2042
  return true; // 出错时返回 true,保守处理
@@ -1622,16 +2078,16 @@ class ScreenshotManager {
1622
2078
  // 并发处理当前批次
1623
2079
  await Promise.all(batch.map(async (img) => {
1624
2080
  const originalSrc = img.src;
1625
- // 检查缓存
1626
- if (this.imageProxyCache.has(originalSrc)) {
2081
+ // 检查缓存(带过期时间)
2082
+ if (this.getCachedImage(originalSrc)) {
1627
2083
  return;
1628
2084
  }
1629
2085
  try {
1630
2086
  // 使用代理服务器获取图片
1631
2087
  const dataUrl = await this.proxyImage(originalSrc);
1632
2088
  if (dataUrl) {
1633
- // 缓存 data URL
1634
- this.imageProxyCache.set(originalSrc, dataUrl);
2089
+ // 缓存 data URL(带时间戳)
2090
+ this.setCachedImage(originalSrc, dataUrl);
1635
2091
  }
1636
2092
  }
1637
2093
  catch (error) {
@@ -1712,7 +2168,7 @@ class ScreenshotManager {
1712
2168
  });
1713
2169
  }
1714
2170
  /**
1715
- * 等待图片加载完成
2171
+ * 等待图片加载完成(优化:使用更短的超时和 Promise.race)
1716
2172
  */
1717
2173
  async waitForImagesToLoad(element) {
1718
2174
  const images = element.querySelectorAll('img');
@@ -1721,32 +2177,33 @@ class ScreenshotManager {
1721
2177
  if (img.complete) {
1722
2178
  return;
1723
2179
  }
1724
- imagePromises.push(new Promise((resolve) => {
1725
- const timeout = setTimeout(() => {
1726
- resolve();
1727
- }, 5000);
1728
- img.onload = () => {
1729
- clearTimeout(timeout);
1730
- resolve();
1731
- };
1732
- img.onerror = () => {
1733
- clearTimeout(timeout);
1734
- resolve();
1735
- };
1736
- }));
2180
+ // 使用更短的超时时间(可配置)
2181
+ const timeout = this.options.imageLoadTimeout || 5000;
2182
+ imagePromises.push(Promise.race([
2183
+ new Promise((resolve) => {
2184
+ img.onload = () => resolve();
2185
+ img.onerror = () => resolve(); // 失败也继续
2186
+ }),
2187
+ new Promise((resolve) => {
2188
+ setTimeout(() => resolve(), timeout);
2189
+ })
2190
+ ]));
1737
2191
  });
1738
2192
  if (imagePromises.length > 0) {
1739
2193
  await Promise.all(imagePromises);
1740
2194
  }
1741
2195
  }
1742
2196
  /**
1743
- * 等待 CSS 和字体加载完成
2197
+ * 等待 CSS 和字体加载完成(优化:减少等待时间,使用 requestAnimationFrame)
1744
2198
  */
1745
2199
  async waitForStylesAndFonts() {
2200
+ // 使用 requestAnimationFrame 优化渲染时机
1746
2201
  return new Promise((resolve) => {
1747
- setTimeout(() => {
1748
- resolve();
1749
- }, 100);
2202
+ requestAnimationFrame(() => {
2203
+ setTimeout(() => {
2204
+ resolve();
2205
+ }, 30); // 减少到30ms
2206
+ });
1750
2207
  });
1751
2208
  }
1752
2209
  /**
@@ -1966,9 +2423,86 @@ class ScreenshotManager {
1966
2423
  this.messageHandler = null;
1967
2424
  }
1968
2425
  this.removeGlobalErrorHandlers();
2426
+ // 清理 Intersection Observer
2427
+ if (this.intersectionObserver) {
2428
+ this.intersectionObserver.disconnect();
2429
+ this.intersectionObserver = null;
2430
+ this.visibleElementsCache.clear();
2431
+ }
2432
+ // 关闭 IndexedDB
2433
+ if (this.indexedDBCache) {
2434
+ this.indexedDBCache.close();
2435
+ this.indexedDBCache = null;
2436
+ this.indexedDBReady = false;
2437
+ }
1969
2438
  // 清理图片代理缓存
1970
2439
  this.imageProxyCache.clear();
1971
2440
  }
2441
+ /**
2442
+ * 获取缓存的图片(检查是否过期)
2443
+ */
2444
+ getCachedImage(url) {
2445
+ const cached = this.imageProxyCache.get(url);
2446
+ if (!cached) {
2447
+ return null;
2448
+ }
2449
+ // 检查是否过期(10分钟)
2450
+ const now = Date.now();
2451
+ const age = now - cached.timestamp;
2452
+ if (age > this.options.imageCacheTTL) {
2453
+ // 缓存已过期,删除
2454
+ this.imageProxyCache.delete(url);
2455
+ return null;
2456
+ }
2457
+ return cached.dataUrl;
2458
+ }
2459
+ /**
2460
+ * 设置缓存的图片(带时间戳)
2461
+ */
2462
+ setCachedImage(url, dataUrl) {
2463
+ this.imageProxyCache.set(url, {
2464
+ dataUrl,
2465
+ timestamp: Date.now()
2466
+ });
2467
+ }
2468
+ /**
2469
+ * 清理过期缓存
2470
+ */
2471
+ cleanExpiredCache() {
2472
+ const now = Date.now();
2473
+ const expiredUrls = [];
2474
+ this.imageProxyCache.forEach((cached, url) => {
2475
+ const age = now - cached.timestamp;
2476
+ if (age > this.options.imageCacheTTL) {
2477
+ expiredUrls.push(url);
2478
+ }
2479
+ });
2480
+ expiredUrls.forEach(url => {
2481
+ this.imageProxyCache.delete(url);
2482
+ });
2483
+ if (expiredUrls.length > 0 && !this.options.silentMode) {
2484
+ console.log(`📸 清理了 ${expiredUrls.length} 个过期缓存`);
2485
+ }
2486
+ }
2487
+ /**
2488
+ * 定期清理过期缓存(可选,在截图时也会自动清理)
2489
+ */
2490
+ startCacheCleanup() {
2491
+ // 每5分钟清理一次过期缓存
2492
+ setInterval(() => {
2493
+ this.cleanExpiredCache();
2494
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
2495
+ if (this.options.useIndexedDB) {
2496
+ this.cleanIndexedDBCache().catch(() => {
2497
+ // 清理失败,忽略
2498
+ });
2499
+ }
2500
+ if (!this.options.silentMode) {
2501
+ const memoryCacheSize = this.imageProxyCache.size;
2502
+ console.log(`📸 清理过期缓存,内存缓存数量: ${memoryCacheSize}`);
2503
+ }
2504
+ }, 300000); // 5分钟
2505
+ }
1972
2506
  /**
1973
2507
  * 获取状态
1974
2508
  */