customer-chat-sdk 1.0.27 → 1.0.29

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.
@@ -922,28 +922,6 @@ class IframeManager {
922
922
  }
923
923
 
924
924
  // @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
925
  /**
948
926
  * 截图管理器
949
927
  * 负责页面截图、压缩和上传功能
@@ -973,8 +951,16 @@ class ScreenshotManager {
973
951
  this.dynamicInterval = null;
974
952
  // 过期定时器
975
953
  this.expirationTimer = null;
976
- // 图片代理缓存
954
+ // 图片代理缓存(带过期时间)
977
955
  this.imageProxyCache = new Map();
956
+ // IndexedDB 缓存(持久化)
957
+ this.indexedDBCache = null;
958
+ this.indexedDBReady = false;
959
+ // Intersection Observer(用于高效检测可见性)
960
+ this.intersectionObserver = null;
961
+ this.visibleElementsCache = new Set();
962
+ // 预连接状态
963
+ this.preconnected = false;
978
964
  // 全局错误处理器
979
965
  this.globalErrorHandler = null;
980
966
  this.globalRejectionHandler = null;
@@ -993,10 +979,40 @@ class ScreenshotManager {
993
979
  engine: options.engine ?? 'modern-screenshot',
994
980
  corsMode: options.corsMode ?? 'canvas-proxy',
995
981
  silentMode: options.silentMode ?? false,
996
- maxRetries: options.maxRetries ?? 2
982
+ maxRetries: options.maxRetries ?? 2,
983
+ preloadImages: options.preloadImages ?? false, // 默认不预加载,按需加载
984
+ maxConcurrentDownloads: options.maxConcurrentDownloads ?? 10, // 增加并发数
985
+ onlyVisibleImages: options.onlyVisibleImages ?? true, // 默认只处理可视区域
986
+ imageCacheTTL: options.imageCacheTTL ?? 600000, // 默认10分钟(600000ms)
987
+ useIndexedDB: options.useIndexedDB ?? true, // 默认启用 IndexedDB 持久化缓存
988
+ usePreconnect: options.usePreconnect ?? true, // 默认预连接代理服务器
989
+ imageLoadTimeout: options.imageLoadTimeout ?? 5000, // 默认5秒超时
990
+ useIntersectionObserver: options.useIntersectionObserver ?? true, // 默认使用 Intersection Observer
991
+ fetchPriority: options.fetchPriority ?? 'high', // 默认高优先级
992
+ maxCacheSize: options.maxCacheSize ?? 50, // 默认最大50MB
993
+ maxCacheAge: options.maxCacheAge ?? 86400000 // 默认24小时(86400000ms)
997
994
  };
998
995
  this.setupMessageListener();
999
996
  this.setupVisibilityChangeListener();
997
+ // 启动缓存清理定时器
998
+ this.startCacheCleanup();
999
+ // 预连接代理服务器(如果启用)
1000
+ if (this.options.usePreconnect && this.options.proxyUrl) {
1001
+ this.preconnectProxy();
1002
+ }
1003
+ // 初始化 Intersection Observer(如果启用)
1004
+ if (this.options.useIntersectionObserver && this.options.onlyVisibleImages) {
1005
+ this.initIntersectionObserver();
1006
+ }
1007
+ // 初始化 IndexedDB(如果启用)
1008
+ if (this.options.useIndexedDB) {
1009
+ this.initIndexedDB().catch(() => {
1010
+ // IndexedDB 初始化失败,回退到内存缓存
1011
+ if (!this.options.silentMode) {
1012
+ console.warn('📸 IndexedDB 初始化失败,使用内存缓存');
1013
+ }
1014
+ });
1015
+ }
1000
1016
  }
1001
1017
  /**
1002
1018
  * 设置目标元素
@@ -1305,14 +1321,28 @@ class ScreenshotManager {
1305
1321
  if (!this.options.silentMode) {
1306
1322
  console.log(`📸 使用截图引擎: ${selectedEngine} (Worker 模式)`);
1307
1323
  }
1308
- // 预处理网络图片
1309
- if (this.options.enableCORS) {
1324
+ // 优化:如果启用预加载,才预处理图片;否则让 modern-screenshot 按需加载
1325
+ if (this.options.preloadImages && this.options.enableCORS) {
1326
+ // 清理过期缓存
1327
+ this.cleanExpiredCache();
1328
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
1329
+ if (this.options.useIndexedDB) {
1330
+ await this.cleanIndexedDBCache();
1331
+ }
1310
1332
  await this.preprocessNetworkImages(this.targetElement);
1311
1333
  await this.waitForImagesToLoad(this.targetElement);
1312
1334
  }
1335
+ else {
1336
+ // 即使不预加载,也清理一下过期缓存
1337
+ this.cleanExpiredCache();
1338
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
1339
+ if (this.options.useIndexedDB) {
1340
+ await this.cleanIndexedDBCache();
1341
+ }
1342
+ }
1313
1343
  let dataUrl;
1314
- // 等待一小段时间,确保 DOM 更新完成
1315
- await new Promise(resolve => setTimeout(resolve, 100));
1344
+ // 等待一小段时间,确保 DOM 更新完成(减少等待时间)
1345
+ await new Promise(resolve => setTimeout(resolve, 50));
1316
1346
  // 使用 modern-screenshot 截图(启用 Worker)
1317
1347
  dataUrl = await this.takeScreenshotWithModernScreenshot(this.targetElement);
1318
1348
  const timestamp = Date.now();
@@ -1409,9 +1439,25 @@ class ScreenshotManager {
1409
1439
  }
1410
1440
  // 如果配置了代理服务器,使用代理处理跨域图片
1411
1441
  if (this.options.proxyUrl && this.options.proxyUrl.trim() !== '') {
1412
- // 检查缓存
1413
- if (this.imageProxyCache.has(url)) {
1414
- return this.imageProxyCache.get(url);
1442
+ // 检查内存缓存(优先使用缓存,带过期时间检查)
1443
+ const cachedDataUrl = this.getCachedImage(url);
1444
+ if (cachedDataUrl) {
1445
+ if (!this.options.silentMode) {
1446
+ console.log(`📸 ✅ 使用内存缓存图片: ${url.substring(0, 50)}...`);
1447
+ }
1448
+ return cachedDataUrl;
1449
+ }
1450
+ // 检查 IndexedDB 缓存(如果启用)
1451
+ if (this.options.useIndexedDB) {
1452
+ const indexedDBCache = await this.getIndexedDBCache(url);
1453
+ if (indexedDBCache) {
1454
+ // 同步到内存缓存
1455
+ this.setCachedImage(url, indexedDBCache);
1456
+ if (!this.options.silentMode) {
1457
+ console.log(`📸 ✅ 使用 IndexedDB 缓存图片: ${url.substring(0, 50)}...`);
1458
+ }
1459
+ return indexedDBCache;
1460
+ }
1415
1461
  }
1416
1462
  try {
1417
1463
  // 构建代理请求参数
@@ -1425,24 +1471,43 @@ class ScreenshotManager {
1425
1471
  let baseUrl = this.options.proxyUrl;
1426
1472
  baseUrl = baseUrl.replace(/[?&]$/, '');
1427
1473
  const proxyUrl = `${baseUrl}?${params.toString()}`;
1428
- // 请求代理服务器
1429
- const response = await fetch(proxyUrl, {
1430
- method: 'GET',
1431
- mode: 'cors',
1432
- credentials: 'omit',
1433
- headers: {
1434
- 'Accept': 'image/*'
1435
- },
1436
- cache: 'no-cache'
1437
- });
1438
- if (!response.ok) {
1439
- throw new Error(`代理请求失败: ${response.status}`);
1474
+ // 请求代理服务器(优化:添加超时控制和优先级)
1475
+ const controller = new AbortController();
1476
+ const timeoutId = setTimeout(() => controller.abort(), this.options.imageLoadTimeout);
1477
+ try {
1478
+ const fetchOptions = {
1479
+ method: 'GET',
1480
+ mode: 'cors',
1481
+ credentials: 'omit',
1482
+ headers: {
1483
+ 'Accept': 'image/*'
1484
+ },
1485
+ cache: 'no-cache',
1486
+ signal: controller.signal
1487
+ };
1488
+ // 添加 fetch priority(如果支持)
1489
+ if ('priority' in fetchOptions) {
1490
+ fetchOptions.priority = this.options.fetchPriority;
1491
+ }
1492
+ const response = await fetch(proxyUrl, fetchOptions);
1493
+ clearTimeout(timeoutId);
1494
+ if (!response.ok) {
1495
+ throw new Error(`代理请求失败: ${response.status}`);
1496
+ }
1497
+ const blob = await response.blob();
1498
+ const dataUrl = await this.blobToDataUrl(blob);
1499
+ // 缓存结果(带时间戳,10分钟有效)
1500
+ this.setCachedImage(url, dataUrl);
1501
+ // 如果启用 IndexedDB,也保存到 IndexedDB
1502
+ if (this.options.useIndexedDB) {
1503
+ await this.setIndexedDBCache(url, dataUrl);
1504
+ }
1505
+ return dataUrl;
1506
+ }
1507
+ catch (fetchError) {
1508
+ clearTimeout(timeoutId);
1509
+ throw fetchError;
1440
1510
  }
1441
- const blob = await response.blob();
1442
- const dataUrl = await this.blobToDataUrl(blob);
1443
- // 缓存结果
1444
- this.imageProxyCache.set(url, dataUrl);
1445
- return dataUrl;
1446
1511
  }
1447
1512
  catch (error) {
1448
1513
  if (!this.options.silentMode) {
@@ -1483,11 +1548,7 @@ class ScreenshotManager {
1483
1548
  if (this.options.scale !== 1) {
1484
1549
  contextOptions.scale = isMobile ? 0.8 : this.options.scale;
1485
1550
  }
1486
- // 尝试设置 workerUrl(如果可用)
1487
- const resolvedWorkerUrl = await getWorkerUrl();
1488
- if (resolvedWorkerUrl) {
1489
- contextOptions.workerUrl = resolvedWorkerUrl;
1490
- }
1551
+ // modern-screenshot 会自动处理 worker URL,不需要手动设置
1491
1552
  // 创建 Worker 上下文
1492
1553
  this.screenshotContext = await createContext(element, contextOptions);
1493
1554
  }
@@ -1551,76 +1612,399 @@ class ScreenshotManager {
1551
1612
  }
1552
1613
  }
1553
1614
  /**
1554
- * 预处理网络图片
1615
+ * 预连接代理服务器(优化网络性能)
1616
+ */
1617
+ preconnectProxy() {
1618
+ if (this.preconnected || !this.options.proxyUrl) {
1619
+ return;
1620
+ }
1621
+ try {
1622
+ const proxyOrigin = new URL(this.options.proxyUrl).origin;
1623
+ const link = document.createElement('link');
1624
+ link.rel = 'preconnect';
1625
+ link.href = proxyOrigin;
1626
+ link.crossOrigin = 'anonymous';
1627
+ document.head.appendChild(link);
1628
+ this.preconnected = true;
1629
+ if (!this.options.silentMode) {
1630
+ console.log(`📸 ✅ 已预连接代理服务器: ${proxyOrigin}`);
1631
+ }
1632
+ }
1633
+ catch (e) {
1634
+ // 预连接失败,不影响功能
1635
+ }
1636
+ }
1637
+ /**
1638
+ * 初始化 Intersection Observer(优化可见性检测)
1639
+ */
1640
+ initIntersectionObserver() {
1641
+ if (!('IntersectionObserver' in window)) {
1642
+ return;
1643
+ }
1644
+ this.intersectionObserver = new IntersectionObserver((entries) => {
1645
+ entries.forEach((entry) => {
1646
+ if (entry.isIntersecting) {
1647
+ this.visibleElementsCache.add(entry.target);
1648
+ }
1649
+ else {
1650
+ this.visibleElementsCache.delete(entry.target);
1651
+ }
1652
+ });
1653
+ }, {
1654
+ root: null,
1655
+ rootMargin: '50px', // 提前50px开始加载
1656
+ threshold: 0.01
1657
+ });
1658
+ }
1659
+ /**
1660
+ * 初始化 IndexedDB(持久化缓存)
1661
+ */
1662
+ async initIndexedDB() {
1663
+ return new Promise((resolve, reject) => {
1664
+ const request = indexedDB.open('screenshot-cache', 1);
1665
+ request.onerror = () => reject(request.error);
1666
+ request.onsuccess = () => {
1667
+ this.indexedDBCache = request.result;
1668
+ this.indexedDBReady = true;
1669
+ // 初始化后立即清理过期和超大小的缓存
1670
+ this.cleanIndexedDBCache().catch(() => {
1671
+ // 清理失败不影响功能
1672
+ });
1673
+ resolve();
1674
+ };
1675
+ request.onupgradeneeded = (event) => {
1676
+ const db = event.target.result;
1677
+ if (!db.objectStoreNames.contains('images')) {
1678
+ const store = db.createObjectStore('images', { keyPath: 'url' });
1679
+ // 创建索引用于按时间排序
1680
+ store.createIndex('timestamp', 'timestamp', { unique: false });
1681
+ }
1682
+ };
1683
+ });
1684
+ }
1685
+ /**
1686
+ * 从 IndexedDB 获取缓存
1687
+ */
1688
+ async getIndexedDBCache(url) {
1689
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1690
+ return null;
1691
+ }
1692
+ try {
1693
+ const transaction = this.indexedDBCache.transaction(['images'], 'readonly');
1694
+ const store = transaction.objectStore('images');
1695
+ const request = store.get(url);
1696
+ return new Promise((resolve) => {
1697
+ request.onsuccess = () => {
1698
+ const result = request.result;
1699
+ if (result) {
1700
+ const now = Date.now();
1701
+ const age = now - result.timestamp;
1702
+ // 检查是否超过最大缓存时间
1703
+ if (age > this.options.maxCacheAge) {
1704
+ // 缓存过期,删除
1705
+ this.deleteIndexedDBCache(url);
1706
+ resolve(null);
1707
+ return;
1708
+ }
1709
+ // 返回缓存数据(即使超过 imageCacheTTL,只要未超过 maxCacheAge 仍可使用)
1710
+ resolve(result.dataUrl);
1711
+ }
1712
+ else {
1713
+ resolve(null);
1714
+ }
1715
+ };
1716
+ request.onerror = () => resolve(null);
1717
+ });
1718
+ }
1719
+ catch {
1720
+ return null;
1721
+ }
1722
+ }
1723
+ /**
1724
+ * 设置 IndexedDB 缓存(带大小和时间控制)
1725
+ */
1726
+ async setIndexedDBCache(url, dataUrl) {
1727
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1728
+ return;
1729
+ }
1730
+ try {
1731
+ // 计算当前缓存大小
1732
+ const currentSize = await this.getIndexedDBCacheSize();
1733
+ const newItemSize = this.estimateDataUrlSize(dataUrl);
1734
+ const maxSizeBytes = (this.options.maxCacheSize || 50) * 1024 * 1024; // 转换为字节
1735
+ // 如果添加新项后超过限制,清理最旧的数据
1736
+ if (currentSize + newItemSize > maxSizeBytes) {
1737
+ await this.cleanIndexedDBCacheBySize(maxSizeBytes - newItemSize);
1738
+ }
1739
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1740
+ const store = transaction.objectStore('images');
1741
+ store.put({ url, dataUrl, timestamp: Date.now() });
1742
+ }
1743
+ catch {
1744
+ // IndexedDB 写入失败,忽略
1745
+ }
1746
+ }
1747
+ /**
1748
+ * 估算 data URL 的大小(字节)
1749
+ */
1750
+ estimateDataUrlSize(dataUrl) {
1751
+ // Base64 编码后的大小约为原始大小的 4/3
1752
+ // data:image/xxx;base64, 前缀约 22-30 字节
1753
+ const base64Data = dataUrl.split(',')[1] || '';
1754
+ return Math.ceil(base64Data.length * 0.75) + 30;
1755
+ }
1756
+ /**
1757
+ * 获取 IndexedDB 当前缓存大小(字节)
1758
+ */
1759
+ async getIndexedDBCacheSize() {
1760
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1761
+ return 0;
1762
+ }
1763
+ try {
1764
+ const transaction = this.indexedDBCache.transaction(['images'], 'readonly');
1765
+ const store = transaction.objectStore('images');
1766
+ const request = store.getAll();
1767
+ return new Promise((resolve) => {
1768
+ request.onsuccess = () => {
1769
+ const items = request.result || [];
1770
+ let totalSize = 0;
1771
+ items.forEach((item) => {
1772
+ totalSize += this.estimateDataUrlSize(item.dataUrl);
1773
+ });
1774
+ resolve(totalSize);
1775
+ };
1776
+ request.onerror = () => resolve(0);
1777
+ });
1778
+ }
1779
+ catch {
1780
+ return 0;
1781
+ }
1782
+ }
1783
+ /**
1784
+ * 清理 IndexedDB 缓存(按时间和大小)
1785
+ */
1786
+ async cleanIndexedDBCache() {
1787
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1788
+ return;
1789
+ }
1790
+ try {
1791
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1792
+ const store = transaction.objectStore('images');
1793
+ const index = store.index('timestamp');
1794
+ const request = index.getAll();
1795
+ return new Promise((resolve) => {
1796
+ request.onsuccess = () => {
1797
+ const items = request.result || [];
1798
+ const now = Date.now();
1799
+ const expiredUrls = [];
1800
+ let currentSize = 0;
1801
+ const maxSizeBytes = (this.options.maxCacheSize || 50) * 1024 * 1024;
1802
+ // 按时间排序(最旧的在前)
1803
+ items.sort((a, b) => a.timestamp - b.timestamp);
1804
+ // 清理过期数据
1805
+ items.forEach((item) => {
1806
+ const age = now - item.timestamp;
1807
+ if (age > this.options.maxCacheAge) {
1808
+ expiredUrls.push(item.url);
1809
+ }
1810
+ else {
1811
+ currentSize += this.estimateDataUrlSize(item.dataUrl);
1812
+ }
1813
+ });
1814
+ // 如果仍然超过大小限制,删除最旧的数据
1815
+ const urlsToDelete = [...expiredUrls];
1816
+ if (currentSize > maxSizeBytes) {
1817
+ for (const item of items) {
1818
+ if (expiredUrls.includes(item.url))
1819
+ continue;
1820
+ currentSize -= this.estimateDataUrlSize(item.dataUrl);
1821
+ urlsToDelete.push(item.url);
1822
+ if (currentSize <= maxSizeBytes) {
1823
+ break;
1824
+ }
1825
+ }
1826
+ }
1827
+ // 删除过期和超大小的数据
1828
+ urlsToDelete.forEach((url) => {
1829
+ store.delete(url);
1830
+ });
1831
+ if (urlsToDelete.length > 0 && !this.options.silentMode) {
1832
+ console.log(`📸 IndexedDB 清理了 ${urlsToDelete.length} 个缓存项(过期或超大小)`);
1833
+ }
1834
+ resolve();
1835
+ };
1836
+ request.onerror = () => resolve();
1837
+ });
1838
+ }
1839
+ catch {
1840
+ // 清理失败,忽略
1841
+ }
1842
+ }
1843
+ /**
1844
+ * 按大小清理 IndexedDB 缓存
1845
+ */
1846
+ async cleanIndexedDBCacheBySize(targetSize) {
1847
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1848
+ return;
1849
+ }
1850
+ try {
1851
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1852
+ const store = transaction.objectStore('images');
1853
+ const index = store.index('timestamp');
1854
+ const request = index.getAll();
1855
+ return new Promise((resolve) => {
1856
+ request.onsuccess = () => {
1857
+ const items = request.result || [];
1858
+ // 按时间排序(最旧的在前)
1859
+ items.sort((a, b) => a.timestamp - b.timestamp);
1860
+ let currentSize = 0;
1861
+ const urlsToDelete = [];
1862
+ // 计算当前大小
1863
+ items.forEach((item) => {
1864
+ currentSize += this.estimateDataUrlSize(item.dataUrl);
1865
+ });
1866
+ // 如果超过目标大小,删除最旧的数据
1867
+ if (currentSize > targetSize) {
1868
+ for (const item of items) {
1869
+ if (currentSize <= targetSize) {
1870
+ break;
1871
+ }
1872
+ currentSize -= this.estimateDataUrlSize(item.dataUrl);
1873
+ urlsToDelete.push(item.url);
1874
+ }
1875
+ }
1876
+ // 删除数据
1877
+ urlsToDelete.forEach((url) => {
1878
+ store.delete(url);
1879
+ });
1880
+ if (urlsToDelete.length > 0 && !this.options.silentMode) {
1881
+ console.log(`📸 IndexedDB 清理了 ${urlsToDelete.length} 个缓存项(超过大小限制)`);
1882
+ }
1883
+ resolve();
1884
+ };
1885
+ request.onerror = () => resolve();
1886
+ });
1887
+ }
1888
+ catch {
1889
+ // 清理失败,忽略
1890
+ }
1891
+ }
1892
+ /**
1893
+ * 删除 IndexedDB 缓存
1894
+ */
1895
+ async deleteIndexedDBCache(url) {
1896
+ if (!this.indexedDBReady || !this.indexedDBCache) {
1897
+ return;
1898
+ }
1899
+ try {
1900
+ const transaction = this.indexedDBCache.transaction(['images'], 'readwrite');
1901
+ const store = transaction.objectStore('images');
1902
+ store.delete(url);
1903
+ }
1904
+ catch {
1905
+ // 忽略错误
1906
+ }
1907
+ }
1908
+ /**
1909
+ * 检查元素是否在可视区域内(优化:使用 Intersection Observer 或 getBoundingClientRect)
1910
+ */
1911
+ isElementVisible(element, container) {
1912
+ if (!this.options.onlyVisibleImages) {
1913
+ return true; // 如果禁用可视区域检测,返回 true
1914
+ }
1915
+ // 如果使用 Intersection Observer 且元素已在缓存中,直接返回
1916
+ if (this.options.useIntersectionObserver && this.intersectionObserver) {
1917
+ if (this.visibleElementsCache.has(element)) {
1918
+ return true;
1919
+ }
1920
+ // 观察元素(如果还没有观察)
1921
+ this.intersectionObserver.observe(element);
1922
+ }
1923
+ // 回退到 getBoundingClientRect
1924
+ try {
1925
+ const rect = element.getBoundingClientRect();
1926
+ const containerRect = container.getBoundingClientRect();
1927
+ // 检查元素是否与容器有交集(考虑滚动位置)
1928
+ const isIntersecting = !(rect.bottom < containerRect.top ||
1929
+ rect.top > containerRect.bottom ||
1930
+ rect.right < containerRect.left ||
1931
+ rect.left > containerRect.right) && (rect.width > 0 && rect.height > 0 && // 元素有尺寸
1932
+ window.getComputedStyle(element).display !== 'none' && // 元素可见
1933
+ window.getComputedStyle(element).visibility !== 'hidden' &&
1934
+ window.getComputedStyle(element).opacity !== '0');
1935
+ // 更新 Intersection Observer 缓存
1936
+ if (this.options.useIntersectionObserver && this.intersectionObserver) {
1937
+ if (isIntersecting) {
1938
+ this.visibleElementsCache.add(element);
1939
+ }
1940
+ else {
1941
+ this.visibleElementsCache.delete(element);
1942
+ }
1943
+ }
1944
+ return isIntersecting;
1945
+ }
1946
+ catch {
1947
+ return true; // 出错时返回 true,保守处理
1948
+ }
1949
+ }
1950
+ /**
1951
+ * 预处理网络图片(优化:只处理可视区域内的图片,增加并发数)
1555
1952
  */
1556
1953
  async preprocessNetworkImages(element) {
1557
1954
  const images = element.querySelectorAll('img');
1955
+ // 过滤:只处理跨域图片,并且如果在可视区域内
1558
1956
  const networkImages = Array.from(images).filter(img => {
1559
1957
  const isBlob = img.src.startsWith('blob:');
1560
1958
  const isData = img.src.startsWith('data:');
1561
1959
  const isSameOrigin = img.src.startsWith(window.location.origin);
1562
- return !isBlob && !isData && !isSameOrigin;
1960
+ const isVisible = this.isElementVisible(img, element);
1961
+ return !isBlob && !isData && !isSameOrigin && isVisible;
1563
1962
  });
1564
1963
  if (networkImages.length === 0) {
1565
1964
  return;
1566
1965
  }
1567
1966
  if (!this.options.silentMode) {
1568
- console.log(`📸 发现 ${networkImages.length} 个跨域图片,开始预加载并缓存...`);
1967
+ const totalImages = images.length;
1968
+ console.log(`📸 发现 ${networkImages.length}/${totalImages} 个可视区域内的跨域图片,开始并行预加载...`);
1569
1969
  }
1570
1970
  // 如果配置了 proxyUrl,使用代理处理跨域图片
1571
1971
  if (this.options.proxyUrl && this.options.proxyUrl.trim() !== '') {
1572
1972
  if (!this.options.silentMode) {
1573
1973
  console.log(`📸 使用代理服务器处理跨域图片: ${this.options.proxyUrl}`);
1574
1974
  }
1575
- // 分批处理图片,避免同时处理太多导致主线程阻塞
1576
- const batchSize = 5;
1975
+ // 优化:增加并发数,使用更大的批次
1976
+ const batchSize = this.options.maxConcurrentDownloads || 10;
1577
1977
  const batches = [];
1578
1978
  for (let i = 0; i < networkImages.length; i += batchSize) {
1579
1979
  batches.push(networkImages.slice(i, i + batchSize));
1580
1980
  }
1581
- for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
1582
- const batch = batches[batchIndex];
1583
- // 如果不是第一批,等待浏览器空闲时间
1584
- if (batchIndex > 0) {
1585
- await new Promise((resolve) => {
1586
- if ('requestIdleCallback' in window) {
1587
- requestIdleCallback(() => resolve(), { timeout: 100 });
1588
- }
1589
- else {
1590
- setTimeout(() => resolve(), 50);
1591
- }
1592
- });
1593
- }
1981
+ // 并行处理所有批次(不再等待空闲时间)
1982
+ await Promise.all(batches.map(async (batch) => {
1594
1983
  // 并发处理当前批次
1595
1984
  await Promise.all(batch.map(async (img) => {
1596
1985
  const originalSrc = img.src;
1597
- // 检查缓存
1598
- if (this.imageProxyCache.has(originalSrc)) {
1599
- if (!this.options.silentMode) {
1600
- console.log(`📸 使用缓存的代理图片: ${originalSrc.substring(0, 100)}...`);
1601
- }
1986
+ // 检查缓存(带过期时间)
1987
+ if (this.getCachedImage(originalSrc)) {
1602
1988
  return;
1603
1989
  }
1604
1990
  try {
1605
1991
  // 使用代理服务器获取图片
1606
1992
  const dataUrl = await this.proxyImage(originalSrc);
1607
1993
  if (dataUrl) {
1608
- // 缓存 data URL
1609
- this.imageProxyCache.set(originalSrc, dataUrl);
1610
- if (!this.options.silentMode) {
1611
- console.log(`📸 ✅ 代理预加载成功(已缓存): ${originalSrc.substring(0, 100)}...`);
1612
- }
1994
+ // 缓存 data URL(带时间戳)
1995
+ this.setCachedImage(originalSrc, dataUrl);
1613
1996
  }
1614
1997
  }
1615
1998
  catch (error) {
1999
+ // 静默失败,不影响其他图片
1616
2000
  if (!this.options.silentMode) {
1617
- console.warn(`📸 ❌ 代理预加载失败: ${originalSrc.substring(0, 100)}...`, error);
2001
+ console.warn(`📸 ❌ 代理预加载失败: ${originalSrc.substring(0, 50)}...`);
1618
2002
  }
1619
2003
  }
1620
2004
  }));
1621
- }
2005
+ }));
1622
2006
  if (!this.options.silentMode) {
1623
- console.log(`📸 预处理完成,缓存了 ${this.imageProxyCache.size} 个代理图片`);
2007
+ console.log(`📸 预处理完成,缓存了 ${this.imageProxyCache.size} 个代理图片`);
1624
2008
  }
1625
2009
  }
1626
2010
  }
@@ -1689,7 +2073,7 @@ class ScreenshotManager {
1689
2073
  });
1690
2074
  }
1691
2075
  /**
1692
- * 等待图片加载完成
2076
+ * 等待图片加载完成(优化:使用更短的超时和 Promise.race)
1693
2077
  */
1694
2078
  async waitForImagesToLoad(element) {
1695
2079
  const images = element.querySelectorAll('img');
@@ -1698,32 +2082,33 @@ class ScreenshotManager {
1698
2082
  if (img.complete) {
1699
2083
  return;
1700
2084
  }
1701
- imagePromises.push(new Promise((resolve) => {
1702
- const timeout = setTimeout(() => {
1703
- resolve();
1704
- }, 5000);
1705
- img.onload = () => {
1706
- clearTimeout(timeout);
1707
- resolve();
1708
- };
1709
- img.onerror = () => {
1710
- clearTimeout(timeout);
1711
- resolve();
1712
- };
1713
- }));
2085
+ // 使用更短的超时时间(可配置)
2086
+ const timeout = this.options.imageLoadTimeout || 5000;
2087
+ imagePromises.push(Promise.race([
2088
+ new Promise((resolve) => {
2089
+ img.onload = () => resolve();
2090
+ img.onerror = () => resolve(); // 失败也继续
2091
+ }),
2092
+ new Promise((resolve) => {
2093
+ setTimeout(() => resolve(), timeout);
2094
+ })
2095
+ ]));
1714
2096
  });
1715
2097
  if (imagePromises.length > 0) {
1716
2098
  await Promise.all(imagePromises);
1717
2099
  }
1718
2100
  }
1719
2101
  /**
1720
- * 等待 CSS 和字体加载完成
2102
+ * 等待 CSS 和字体加载完成(优化:减少等待时间,使用 requestAnimationFrame)
1721
2103
  */
1722
2104
  async waitForStylesAndFonts() {
2105
+ // 使用 requestAnimationFrame 优化渲染时机
1723
2106
  return new Promise((resolve) => {
1724
- setTimeout(() => {
1725
- resolve();
1726
- }, 100);
2107
+ requestAnimationFrame(() => {
2108
+ setTimeout(() => {
2109
+ resolve();
2110
+ }, 30); // 减少到30ms
2111
+ });
1727
2112
  });
1728
2113
  }
1729
2114
  /**
@@ -1943,9 +2328,86 @@ class ScreenshotManager {
1943
2328
  this.messageHandler = null;
1944
2329
  }
1945
2330
  this.removeGlobalErrorHandlers();
2331
+ // 清理 Intersection Observer
2332
+ if (this.intersectionObserver) {
2333
+ this.intersectionObserver.disconnect();
2334
+ this.intersectionObserver = null;
2335
+ this.visibleElementsCache.clear();
2336
+ }
2337
+ // 关闭 IndexedDB
2338
+ if (this.indexedDBCache) {
2339
+ this.indexedDBCache.close();
2340
+ this.indexedDBCache = null;
2341
+ this.indexedDBReady = false;
2342
+ }
1946
2343
  // 清理图片代理缓存
1947
2344
  this.imageProxyCache.clear();
1948
2345
  }
2346
+ /**
2347
+ * 获取缓存的图片(检查是否过期)
2348
+ */
2349
+ getCachedImage(url) {
2350
+ const cached = this.imageProxyCache.get(url);
2351
+ if (!cached) {
2352
+ return null;
2353
+ }
2354
+ // 检查是否过期(10分钟)
2355
+ const now = Date.now();
2356
+ const age = now - cached.timestamp;
2357
+ if (age > this.options.imageCacheTTL) {
2358
+ // 缓存已过期,删除
2359
+ this.imageProxyCache.delete(url);
2360
+ return null;
2361
+ }
2362
+ return cached.dataUrl;
2363
+ }
2364
+ /**
2365
+ * 设置缓存的图片(带时间戳)
2366
+ */
2367
+ setCachedImage(url, dataUrl) {
2368
+ this.imageProxyCache.set(url, {
2369
+ dataUrl,
2370
+ timestamp: Date.now()
2371
+ });
2372
+ }
2373
+ /**
2374
+ * 清理过期缓存
2375
+ */
2376
+ cleanExpiredCache() {
2377
+ const now = Date.now();
2378
+ const expiredUrls = [];
2379
+ this.imageProxyCache.forEach((cached, url) => {
2380
+ const age = now - cached.timestamp;
2381
+ if (age > this.options.imageCacheTTL) {
2382
+ expiredUrls.push(url);
2383
+ }
2384
+ });
2385
+ expiredUrls.forEach(url => {
2386
+ this.imageProxyCache.delete(url);
2387
+ });
2388
+ if (expiredUrls.length > 0 && !this.options.silentMode) {
2389
+ console.log(`📸 清理了 ${expiredUrls.length} 个过期缓存`);
2390
+ }
2391
+ }
2392
+ /**
2393
+ * 定期清理过期缓存(可选,在截图时也会自动清理)
2394
+ */
2395
+ startCacheCleanup() {
2396
+ // 每5分钟清理一次过期缓存
2397
+ setInterval(() => {
2398
+ this.cleanExpiredCache();
2399
+ // 如果启用 IndexedDB,也清理 IndexedDB 缓存
2400
+ if (this.options.useIndexedDB) {
2401
+ this.cleanIndexedDBCache().catch(() => {
2402
+ // 清理失败,忽略
2403
+ });
2404
+ }
2405
+ if (!this.options.silentMode) {
2406
+ const memoryCacheSize = this.imageProxyCache.size;
2407
+ console.log(`📸 清理过期缓存,内存缓存数量: ${memoryCacheSize}`);
2408
+ }
2409
+ }, 300000); // 5分钟
2410
+ }
1949
2411
  /**
1950
2412
  * 获取状态
1951
2413
  */