customer-chat-sdk 1.0.34 → 1.0.36

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.
@@ -2,6 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var html2canvas = require('html2canvas');
6
+
5
7
  // 直接使用base64字符串,避免打包后路径问题
6
8
  const iconImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAArKSURBVHgB7Z1NbFTXFcf/93mwaGyEabLoIgFTqWRFMZUitSoIu80ial01SFWrKgsGKXYpWdRtFilRK4xUgbKICosmCKIySKCo2UAE6i61XVroDuOoi2YT02RZVFNwQTAzN+e8N88ej9+8j5n3ce5wf5JhPvyY4f3f/9xzz73vXoUeYKish6oljCiFYQ2MaAebVR3D/Jzf1xpDUPTTggIW6feXoOlH0Q9wS9exRK/Pl6qYX6qoJRiOgoEMvqpHWUjlYJ9iQeEJmTb07y6y2CT6HP99/z01C8MwQmB26OMSyuTIH9LTkSA35oLn9FmKCB/WHmP2YUUtQjhiBV4jqsIoJKJJbOC8ZLHFCczhl75UWXvCFuPUDiBXV5TGeWlhXIzALCx9m6Ni3RqfeRL71PJZVYEAChfYdayDc1klSkXBCRr9caxooQsTuIccG4qbiddxsKjQnbvAlDwNVzfgXK8L2wq30ZSMHcs7GctV4IFX9ZTyXGtM8pQq2i2qnCQ3H0NO5CLwk+radnDYrj3CWB5udpAx7FoS96YVdxVy1XCJzgmfG2RMZg5268P9FI6BzP8TRlN3Q/YvkRGZCOyG5H5cApcVLZFkGbJTF3igrEccErfX+rVZk5XIqbbBmyb1y2oDZqy4yfHbZT6HSJHUHDwwqQ/QP1aBpWvIIOXlM+o8UiAVga246ZOWyF0LbMXNjjRE7kpgbi/oS1yCJTNIoP33zqjL6JCOB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vcMd9ajAgbKfASVUa0DdXy0DjVWrUKIvbyKzbhkkNUYtVM7LsLbagWAodmB2Nxfz22wDZUy0BTnzdOaPZJdH8whYWTHPthKQY698vvkQYJSLwEGq9BXO13N68UvztpL5Gk3W0m8R3+PGZccrCfroxFWHKBxU3S7jbT8SKGAxN6hA6ekTaXuuegpKrah91J2t1mOl6jY/msmlfKDkhkDZ/jTsVlulqE5d4ZdVlpK3JWUMZ8kM8xuiCVdWY3TegydaHOwZIaLC5FyQq6JLWFhK3I6ZGWuExq62Tdoy9EV8t+W+3qAjp3fA7TEpdJfSnwoUN6uFbHjJ3ukwzuCtEfLG6qN+mkvtIdlzT7qM9m+8mJmOd+btriMpksZeiK/Ai7bVkzBnSOSk9hrJuuUBiZ79YwMKmnqCt11BZEWqD2lgcOktaWk5LLdhy2XV7HXNVBOSvXNpPrfiuDk3qartxfPLFuzsm1zeS+oU7DzdPk5sLvf8qZ3FzbTGE7JvG28qqOc09A2J6jVHbanaFaAAVvieVVwOhbHO01oblfqxwcLEpYn8IF9mmUOqfooYjdyLugUMe2IkZgn0boLhvVRnPy5OAyDe2dlyKsjziBfdxkrIZRcnWZnu6DTOZ0HZc3DKKydFKJrMGLFbiZFbGBl8FiF9XN4oEUhVvSRW3GCIFb4TDOW9NTSByln11ZJWi8zDKvxMsLe/J6ntLCbxyMFLiVoSk9VH2IEVd03rKedzX3XD7EO3AG7gvlDc3ddR8qLLpZr6LX6iRoHxZLGzFvgkOj+ALBlx6CtCZy6AAAAABJRU5ErkJggg==';
7
9
  class IconManager {
@@ -6898,25 +6900,62 @@ class ScreenshotManager {
6898
6900
  }
6899
6901
  }
6900
6902
  let dataUrl;
6901
- // 等待一小段时间,确保 DOM 更新完成(减少等待时间)
6902
- await new Promise(resolve => setTimeout(resolve, 50));
6903
6903
  // 根据选择的引擎进行截图
6904
- if (selectedEngine === 'snapdom') {
6904
+ if (selectedEngine === 'html2canvas') {
6905
+ // html2canvas 需要更长的等待时间确保样式加载
6906
+ // 额外等待样式和字体加载完成
6907
+ await Promise.all([
6908
+ this.waitForStylesAndFonts(),
6909
+ this.waitForFonts()
6910
+ ]);
6911
+ // 再等待一段时间,确保样式完全应用
6912
+ await new Promise(resolve => setTimeout(resolve, 200));
6913
+ dataUrl = await this.takeScreenshotWithHtml2Canvas(this.targetElement);
6914
+ }
6915
+ else if (selectedEngine === 'snapdom') {
6916
+ // 等待一小段时间,确保 DOM 更新完成
6917
+ await new Promise(resolve => setTimeout(resolve, 50));
6905
6918
  dataUrl = await this.takeScreenshotWithSnapdom(this.targetElement);
6906
6919
  }
6907
6920
  else {
6908
6921
  // 默认使用 modern-screenshot
6922
+ // 等待一小段时间,确保 DOM 更新完成
6923
+ await new Promise(resolve => setTimeout(resolve, 50));
6909
6924
  dataUrl = await this.takeScreenshotWithModernScreenshot(this.targetElement);
6910
6925
  }
6911
6926
  const timestamp = Date.now();
6912
6927
  // 更新状态
6913
6928
  this.screenshotCount++;
6914
6929
  this.lastScreenshotTime = timestamp;
6915
- // 管理历史记录
6930
+ // 管理历史记录(限制内存占用)
6931
+ // base64 字符串很大,需要严格控制历史记录数量
6916
6932
  if (this.screenshotHistory.length >= this.options.maxHistory) {
6917
- this.screenshotHistory.shift();
6933
+ // 删除最旧的截图,释放内存
6934
+ const removed = this.screenshotHistory.shift();
6935
+ // 强制 GC(如果可能)
6936
+ if (removed && removed.length > 1000000) { // 大于1MB的字符串
6937
+ if (!this.options.silentMode) {
6938
+ console.log(`📸 清理旧截图,释放内存: ${Math.round(removed.length * 0.75 / 1024)} KB`);
6939
+ }
6940
+ }
6918
6941
  }
6919
6942
  this.screenshotHistory.push(dataUrl);
6943
+ // 如果历史记录总大小超过限制,清理最旧的
6944
+ let totalSize = this.screenshotHistory.reduce((sum, item) => sum + item.length, 0);
6945
+ const maxTotalSize = 50 * 1024 * 1024; // 最大50MB
6946
+ while (this.screenshotHistory.length > 0 && totalSize > maxTotalSize) {
6947
+ const removed = this.screenshotHistory.shift();
6948
+ if (removed) {
6949
+ const removedSize = removed.length;
6950
+ totalSize -= removedSize;
6951
+ if (!this.options.silentMode) {
6952
+ console.warn(`📸 ⚠️ 历史记录总大小超过限制,清理最旧截图: ${Math.round(removedSize * 0.75 / 1024)} KB`);
6953
+ }
6954
+ }
6955
+ else {
6956
+ break;
6957
+ }
6958
+ }
6920
6959
  // 打印基本信息
6921
6960
  const base64Data = dataUrl.split(',')[1];
6922
6961
  if (!this.options.silentMode) {
@@ -7066,8 +7105,206 @@ class ScreenshotManager {
7066
7105
  throw error;
7067
7106
  }
7068
7107
  }
7108
+ /**
7109
+ * 使用 html2canvas 截图
7110
+ *
7111
+ * 优势:
7112
+ * - 处理 SVG 和本地资源更快(不需要复杂的 Worker 通信)
7113
+ * - 兼容性好,支持更多 CSS 特性
7114
+ * - 跨域处理相对简单
7115
+ *
7116
+ * 劣势:
7117
+ * - 在主线程执行,可能阻塞 UI(但处理速度快,影响较小)
7118
+ * - 不支持 Worker 模式
7119
+ *
7120
+ * 适用场景:
7121
+ * - 页面包含大量 SVG 图标
7122
+ * - 本地资源较多
7123
+ * - 需要快速截图
7124
+ */
7125
+ async takeScreenshotWithHtml2Canvas(element) {
7126
+ if (!this.options.silentMode) {
7127
+ console.log('📸 使用 html2canvas 引擎截图...');
7128
+ }
7129
+ try {
7130
+ // html2canvas 需要确保样式完全加载,额外等待
7131
+ // 等待所有样式表加载完成
7132
+ await this.waitForAllStylesLoaded();
7133
+ // 等待字体加载完成
7134
+ await this.waitForFonts();
7135
+ // 等待 DOM 完全渲染
7136
+ await new Promise(resolve => {
7137
+ requestAnimationFrame(() => {
7138
+ requestAnimationFrame(() => {
7139
+ setTimeout(() => resolve(), 100);
7140
+ });
7141
+ });
7142
+ });
7143
+ // 检查元素是否存在和可见
7144
+ const rect = element.getBoundingClientRect();
7145
+ if (rect.width === 0 || rect.height === 0) {
7146
+ throw new Error('元素尺寸为 0,无法截图');
7147
+ }
7148
+ const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
7149
+ const isLowEndDevice = navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4;
7150
+ // 计算压缩后的尺寸
7151
+ let elementWidth = element.scrollWidth || element.clientWidth || element.offsetWidth;
7152
+ let elementHeight = element.scrollHeight || element.clientHeight || element.offsetHeight;
7153
+ if (element === document.body || element === document.documentElement) {
7154
+ elementWidth = Math.max(element.scrollWidth, element.offsetWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth, window.innerWidth);
7155
+ elementHeight = Math.max(element.scrollHeight, element.offsetHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight, window.innerHeight);
7156
+ }
7157
+ const { width, height } = this.calculateCompressedSize(elementWidth, elementHeight, this.options.maxWidth, this.options.maxHeight);
7158
+ const finalWidth = width < elementWidth ? width : Math.min(elementWidth, this.options.maxWidth);
7159
+ const finalHeight = height < elementHeight ? height : Math.min(elementHeight, this.options.maxHeight);
7160
+ // html2canvas 质量设置(0-1)
7161
+ const finalQuality = isMobile || isLowEndDevice
7162
+ ? Math.max(this.options.quality * 0.65, 0.2)
7163
+ : this.options.quality;
7164
+ // html2canvas 配置选项
7165
+ const options = {
7166
+ // 基本配置
7167
+ backgroundColor: '#ffffff',
7168
+ scale: this.options.scale !== 1 ? (isMobile ? 0.7 : this.options.scale) : (isMobile ? 0.7 : 1),
7169
+ useCORS: this.options.enableCORS,
7170
+ allowTaint: !this.options.enableCORS, // 如果启用 CORS,不允许 taint
7171
+ logging: !this.options.silentMode,
7172
+ width: finalWidth,
7173
+ height: finalHeight,
7174
+ // 关键配置:确保样式正确渲染
7175
+ foreignObjectRendering: false, // 禁用 foreignObject,使用传统渲染方式(更稳定)
7176
+ onclone: (_clonedDoc, _element) => {
7177
+ // 在克隆的文档中,确保所有样式都正确应用
7178
+ // html2canvas 会自动处理样式,这里不需要手动复制
7179
+ // 如果需要,可以在这里添加额外的样式处理逻辑
7180
+ // 复制所有样式表到克隆的文档
7181
+ const originalStyleSheets = Array.from(document.styleSheets);
7182
+ originalStyleSheets.forEach((originalSheet) => {
7183
+ try {
7184
+ // 检查样式表是否可访问
7185
+ if (originalSheet.cssRules) {
7186
+ // 样式表可访问,html2canvas 会自动处理
7187
+ }
7188
+ }
7189
+ catch (e) {
7190
+ // 跨域样式表无法访问,html2canvas 会尝试其他方式
7191
+ }
7192
+ });
7193
+ },
7194
+ // 性能优化
7195
+ removeContainer: true, // 截图后移除临时容器
7196
+ imageTimeout: this.options.imageLoadTimeout || 5000,
7197
+ // 忽略某些元素(可选,提升性能)
7198
+ ignoreElements: (element) => {
7199
+ // 忽略隐藏元素
7200
+ const style = window.getComputedStyle(element);
7201
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
7202
+ return true;
7203
+ }
7204
+ return false;
7205
+ },
7206
+ };
7207
+ // html2canvas 不支持直接的 proxy 选项,需要通过 onclone 钩子处理图片
7208
+ // 如果配置了代理服务器,在克隆时替换图片 URL
7209
+ if (this.options.useProxy && this.options.proxyUrl && this.options.proxyUrl.trim() !== '') {
7210
+ options.onclone = (clonedDoc) => {
7211
+ // 在克隆的文档中,替换所有跨域图片的 src
7212
+ const images = clonedDoc.querySelectorAll('img');
7213
+ images.forEach((img) => {
7214
+ const originalSrc = img.getAttribute('src');
7215
+ if (!originalSrc)
7216
+ return;
7217
+ // 检查是否是跨域图片
7218
+ try {
7219
+ const imgUrl = new URL(originalSrc, window.location.href);
7220
+ if (imgUrl.origin === window.location.origin) {
7221
+ return; // 同源图片,不需要处理
7222
+ }
7223
+ }
7224
+ catch {
7225
+ // URL 解析失败,可能是相对路径,继续处理
7226
+ }
7227
+ // 检查缓存
7228
+ const cachedDataUrl = this.getCachedImage(originalSrc);
7229
+ if (cachedDataUrl) {
7230
+ img.src = cachedDataUrl;
7231
+ return;
7232
+ }
7233
+ // 对于跨域图片,使用代理 URL
7234
+ // html2canvas 会自动处理,但我们可以预先处理
7235
+ // 注意:html2canvas 会自己处理图片加载,这里主要是为了缓存
7236
+ });
7237
+ };
7238
+ }
7239
+ if (!this.options.silentMode) {
7240
+ console.log(`📸 html2canvas 配置: 尺寸 ${finalWidth}x${finalHeight}, 质量 ${finalQuality.toFixed(2)}, 缩放 ${options.scale}`);
7241
+ }
7242
+ // 执行截图
7243
+ const canvas = await html2canvas(element, options);
7244
+ // 根据输出格式转换
7245
+ let mimeType = 'image/png';
7246
+ let finalQualityForExport = undefined;
7247
+ if (this.options.outputFormat === 'webp' && !isMobile) {
7248
+ try {
7249
+ const testCanvas = document.createElement('canvas');
7250
+ testCanvas.width = 1;
7251
+ testCanvas.height = 1;
7252
+ const testDataUrl = testCanvas.toDataURL('image/webp');
7253
+ if (testDataUrl.indexOf('webp') !== -1) {
7254
+ mimeType = 'image/webp';
7255
+ finalQualityForExport = finalQuality;
7256
+ }
7257
+ }
7258
+ catch {
7259
+ mimeType = 'image/jpeg';
7260
+ finalQualityForExport = finalQuality;
7261
+ }
7262
+ }
7263
+ else if (this.options.outputFormat === 'jpeg') {
7264
+ mimeType = 'image/jpeg';
7265
+ finalQualityForExport = finalQuality;
7266
+ }
7267
+ // 转换为 data URL
7268
+ const dataUrl = mimeType === 'image/png'
7269
+ ? canvas.toDataURL(mimeType)
7270
+ : canvas.toDataURL(mimeType, finalQualityForExport);
7271
+ // 验证结果
7272
+ if (!dataUrl || dataUrl.length < 100) {
7273
+ throw new Error('生成的截图数据无效或过短');
7274
+ }
7275
+ if (!this.options.silentMode) {
7276
+ console.log(`📸 html2canvas 截图成功!格式: ${this.options.outputFormat}, 尺寸: ${canvas.width}x${canvas.height}`);
7277
+ }
7278
+ return dataUrl;
7279
+ }
7280
+ catch (error) {
7281
+ const errorMessage = error instanceof Error ? error.message : String(error);
7282
+ if (!this.options.silentMode) {
7283
+ console.error('📸 html2canvas 截图失败:', errorMessage);
7284
+ if (errorMessage.includes('CORS') || errorMessage.includes('cross-origin')) {
7285
+ console.warn('📸 💡 建议:配置 proxyUrl 选项处理跨域图片');
7286
+ }
7287
+ }
7288
+ throw error;
7289
+ }
7290
+ }
7069
7291
  /**
7070
7292
  * 使用 modern-screenshot 截图(启用 Worker)
7293
+ *
7294
+ * 优势:
7295
+ * - 使用 Worker,不阻塞主线程 UI
7296
+ * - 支持并发处理
7297
+ * - 适合复杂页面
7298
+ *
7299
+ * 劣势:
7300
+ * - 处理 SVG 和本地资源较慢(Worker 通信开销)
7301
+ * - 配置相对复杂
7302
+ * - 需要处理 Worker URL
7303
+ *
7304
+ * 适用场景:
7305
+ * - 复杂页面,需要不阻塞 UI
7306
+ * - 需要高质量截图
7307
+ * - 页面资源较少
7071
7308
  */
7072
7309
  async takeScreenshotWithModernScreenshot(element) {
7073
7310
  if (!this.options.silentMode) {
@@ -7360,37 +7597,49 @@ class ScreenshotManager {
7360
7597
  throw new Error('无法获取 canvas context');
7361
7598
  }
7362
7599
  const img = new Image();
7363
- await new Promise((resolve, reject) => {
7364
- img.onload = () => {
7365
- canvas.width = img.width;
7366
- canvas.height = img.height;
7367
- ctx.drawImage(img, 0, 0);
7368
- resolve();
7369
- };
7370
- img.onerror = reject;
7371
- img.src = dataUrl;
7372
- });
7373
- let mimeType = 'image/jpeg';
7374
- // 使用与 createContext 相同的质量设置
7375
- let conversionQuality = finalQuality;
7376
- if (this.options.outputFormat === 'webp' && !isMobile) {
7377
- try {
7378
- const testCanvas = document.createElement('canvas');
7379
- testCanvas.width = 1;
7380
- testCanvas.height = 1;
7381
- const testDataUrl = testCanvas.toDataURL('image/webp');
7382
- if (testDataUrl.indexOf('webp') !== -1) {
7383
- mimeType = 'image/webp';
7600
+ let convertedDataUrl;
7601
+ try {
7602
+ await new Promise((resolve, reject) => {
7603
+ img.onload = () => {
7604
+ canvas.width = img.width;
7605
+ canvas.height = img.height;
7606
+ ctx.drawImage(img, 0, 0);
7607
+ resolve();
7608
+ };
7609
+ img.onerror = reject;
7610
+ img.src = dataUrl;
7611
+ });
7612
+ let mimeType = 'image/jpeg';
7613
+ // 使用与 createContext 相同的质量设置
7614
+ let conversionQuality = finalQuality;
7615
+ if (this.options.outputFormat === 'webp' && !isMobile) {
7616
+ try {
7617
+ const testCanvas = document.createElement('canvas');
7618
+ testCanvas.width = 1;
7619
+ testCanvas.height = 1;
7620
+ const testDataUrl = testCanvas.toDataURL('image/webp');
7621
+ if (testDataUrl.indexOf('webp') !== -1) {
7622
+ mimeType = 'image/webp';
7623
+ }
7624
+ }
7625
+ catch {
7626
+ mimeType = 'image/jpeg';
7384
7627
  }
7385
7628
  }
7386
- catch {
7387
- mimeType = 'image/jpeg';
7388
- }
7629
+ // 使用优化后的质量进行格式转换
7630
+ convertedDataUrl = mimeType === 'image/png'
7631
+ ? canvas.toDataURL(mimeType)
7632
+ : canvas.toDataURL(mimeType, conversionQuality);
7633
+ }
7634
+ finally {
7635
+ // 清理资源,释放内存
7636
+ img.src = ''; // 清除图片引用
7637
+ img.onload = null;
7638
+ img.onerror = null;
7639
+ canvas.width = 0; // 清空 canvas
7640
+ canvas.height = 0;
7641
+ ctx.clearRect(0, 0, 0, 0); // 清除绘制内容
7389
7642
  }
7390
- // 使用优化后的质量进行格式转换
7391
- const convertedDataUrl = mimeType === 'image/png'
7392
- ? canvas.toDataURL(mimeType)
7393
- : canvas.toDataURL(mimeType, conversionQuality);
7394
7643
  return convertedDataUrl;
7395
7644
  }
7396
7645
  return dataUrl;
@@ -7411,15 +7660,34 @@ class ScreenshotManager {
7411
7660
  throw error;
7412
7661
  }
7413
7662
  finally {
7414
- // 每次截图后清理 context,下次重新创建(确保元素状态最新)
7663
+ // 每次截图后立即清理 context,释放 Worker 和内存
7664
+ // 这是防止内存泄漏的关键步骤
7415
7665
  if (this.screenshotContext) {
7416
7666
  try {
7417
7667
  destroyContext(this.screenshotContext);
7668
+ if (!this.options.silentMode) {
7669
+ console.log('📸 ✅ modern-screenshot context 已清理');
7670
+ }
7418
7671
  }
7419
7672
  catch (e) {
7420
- // 忽略清理错误
7673
+ if (!this.options.silentMode) {
7674
+ console.warn('📸 ⚠️ 清理 context 失败:', e);
7675
+ }
7676
+ }
7677
+ finally {
7678
+ // 确保 context 引用被清除
7679
+ this.screenshotContext = null;
7680
+ }
7681
+ }
7682
+ // 强制触发垃圾回收(如果可能)
7683
+ // 注意:这需要浏览器支持,不是所有浏览器都有效
7684
+ if (typeof window !== 'undefined' && window.gc && typeof window.gc === 'function') {
7685
+ try {
7686
+ window.gc();
7687
+ }
7688
+ catch {
7689
+ // 忽略 GC 错误
7421
7690
  }
7422
- this.screenshotContext = null;
7423
7691
  }
7424
7692
  }
7425
7693
  }
@@ -7994,15 +8262,42 @@ class ScreenshotManager {
7994
8262
  }
7995
8263
  }
7996
8264
  /**
7997
- * 等待 CSS 和字体加载完成(优化:减少等待时间,使用 requestAnimationFrame)
8265
+ * 等待 CSS 和字体加载完成
8266
+ * html2canvas 需要确保所有样式表都加载完成才能正确截图
7998
8267
  */
7999
8268
  async waitForStylesAndFonts() {
8000
- // 使用 requestAnimationFrame 优化渲染时机
8001
- return new Promise((resolve) => {
8002
- requestAnimationFrame(() => {
8003
- setTimeout(() => {
8269
+ // 等待所有样式表加载完成
8270
+ const styleSheets = Array.from(document.styleSheets);
8271
+ const styleSheetPromises = styleSheets.map((sheet) => {
8272
+ return new Promise((resolve) => {
8273
+ try {
8274
+ // 检查样式表是否已加载
8275
+ // 尝试访问 cssRules,如果成功说明样式表已加载
8276
+ const rules = sheet.cssRules;
8277
+ if (rules) {
8278
+ resolve();
8279
+ }
8280
+ else {
8281
+ // 如果样式表还在加载,等待一下
8282
+ setTimeout(() => resolve(), 100);
8283
+ }
8284
+ }
8285
+ catch (e) {
8286
+ // 跨域样式表可能无法访问,忽略错误
8004
8287
  resolve();
8005
- }, 30); // 减少到30ms
8288
+ }
8289
+ });
8290
+ });
8291
+ await Promise.all(styleSheetPromises);
8292
+ // 使用 requestAnimationFrame 确保 DOM 已渲染
8293
+ await new Promise((resolve) => {
8294
+ requestAnimationFrame(() => {
8295
+ requestAnimationFrame(() => {
8296
+ // 额外等待,确保样式应用完成
8297
+ setTimeout(() => {
8298
+ resolve();
8299
+ }, 100); // 增加到100ms,确保样式加载
8300
+ });
8006
8301
  });
8007
8302
  });
8008
8303
  }
@@ -8021,6 +8316,52 @@ class ScreenshotManager {
8021
8316
  // 忽略错误
8022
8317
  }
8023
8318
  }
8319
+ /**
8320
+ * 等待所有样式表加载完成(html2canvas 专用)
8321
+ */
8322
+ async waitForAllStylesLoaded() {
8323
+ const styleSheets = Array.from(document.styleSheets);
8324
+ const promises = [];
8325
+ styleSheets.forEach((sheet) => {
8326
+ promises.push(new Promise((resolve) => {
8327
+ try {
8328
+ // 尝试访问样式表规则,如果成功说明样式表已加载
8329
+ const rules = sheet.cssRules;
8330
+ if (rules) {
8331
+ resolve();
8332
+ }
8333
+ else {
8334
+ // 等待样式表加载
8335
+ const checkInterval = setInterval(() => {
8336
+ try {
8337
+ if (sheet.cssRules) {
8338
+ clearInterval(checkInterval);
8339
+ resolve();
8340
+ }
8341
+ }
8342
+ catch {
8343
+ // 跨域样式表无法访问,直接 resolve
8344
+ clearInterval(checkInterval);
8345
+ resolve();
8346
+ }
8347
+ }, 50);
8348
+ // 超时保护(5秒)
8349
+ setTimeout(() => {
8350
+ clearInterval(checkInterval);
8351
+ resolve();
8352
+ }, 5000);
8353
+ }
8354
+ }
8355
+ catch (e) {
8356
+ // 跨域样式表无法访问,直接 resolve
8357
+ resolve();
8358
+ }
8359
+ }));
8360
+ });
8361
+ await Promise.all(promises);
8362
+ // 额外等待,确保样式应用
8363
+ await new Promise(resolve => setTimeout(resolve, 150));
8364
+ }
8024
8365
  /**
8025
8366
  * 计算压缩后的尺寸
8026
8367
  */
@@ -8237,6 +8578,11 @@ class ScreenshotManager {
8237
8578
  }
8238
8579
  // 清理图片代理缓存
8239
8580
  this.imageProxyCache.clear();
8581
+ // 清理截图历史记录(释放大量内存)
8582
+ this.screenshotHistory.length = 0;
8583
+ // 清理图片下载队列
8584
+ this.imageDownloadQueue.clear();
8585
+ this.activeDownloads.clear();
8240
8586
  }
8241
8587
  /**
8242
8588
  * 获取缓存的图片(检查是否过期)
@@ -8258,8 +8604,34 @@ class ScreenshotManager {
8258
8604
  }
8259
8605
  /**
8260
8606
  * 设置缓存的图片(带时间戳)
8607
+ * 添加内存大小限制,防止缓存无限增长
8261
8608
  */
8262
8609
  setCachedImage(url, dataUrl) {
8610
+ // 估算当前缓存总大小(MB)
8611
+ let totalSizeMB = 0;
8612
+ this.imageProxyCache.forEach((cached) => {
8613
+ totalSizeMB += cached.dataUrl.length * 0.75 / (1024 * 1024); // base64 转字节再转MB
8614
+ });
8615
+ // 添加新项的大小
8616
+ const newItemSizeMB = dataUrl.length * 0.75 / (1024 * 1024);
8617
+ const maxCacheSizeMB = 100; // 最大100MB内存缓存
8618
+ // 如果超过限制,清理最旧的缓存
8619
+ if (totalSizeMB + newItemSizeMB > maxCacheSizeMB) {
8620
+ const sortedEntries = Array.from(this.imageProxyCache.entries())
8621
+ .sort((a, b) => a[1].timestamp - b[1].timestamp); // 按时间排序
8622
+ let currentSizeMB = totalSizeMB;
8623
+ for (const [key, value] of sortedEntries) {
8624
+ if (currentSizeMB + newItemSizeMB <= maxCacheSizeMB) {
8625
+ break;
8626
+ }
8627
+ const itemSizeMB = value.dataUrl.length * 0.75 / (1024 * 1024);
8628
+ this.imageProxyCache.delete(key);
8629
+ currentSizeMB -= itemSizeMB;
8630
+ if (!this.options.silentMode) {
8631
+ console.log(`📸 清理内存缓存(超过限制): ${key.substring(0, 50)}...`);
8632
+ }
8633
+ }
8634
+ }
8263
8635
  this.imageProxyCache.set(url, {
8264
8636
  dataUrl,
8265
8637
  timestamp: Date.now()
@@ -8286,9 +8658,10 @@ class ScreenshotManager {
8286
8658
  }
8287
8659
  /**
8288
8660
  * 定期清理过期缓存(可选,在截图时也会自动清理)
8661
+ * 增加清理频率,防止内存积累
8289
8662
  */
8290
8663
  startCacheCleanup() {
8291
- // 每5分钟清理一次过期缓存
8664
+ // 每2分钟清理一次过期缓存(从5分钟改为2分钟,更频繁)
8292
8665
  setInterval(() => {
8293
8666
  this.cleanExpiredCache();
8294
8667
  // 如果启用 IndexedDB,也清理 IndexedDB 缓存
@@ -8299,9 +8672,12 @@ class ScreenshotManager {
8299
8672
  }
8300
8673
  if (!this.options.silentMode) {
8301
8674
  const memoryCacheSize = this.imageProxyCache.size;
8302
- console.log(`📸 清理过期缓存,内存缓存数量: ${memoryCacheSize}`);
8675
+ const memoryCacheSizeMB = Array.from(this.imageProxyCache.values())
8676
+ .reduce((sum, cached) => sum + cached.dataUrl.length * 0.75 / (1024 * 1024), 0);
8677
+ const historySizeMB = this.screenshotHistory.reduce((sum, item) => sum + item.length * 0.75 / (1024 * 1024), 0);
8678
+ console.log(`📸 清理过期缓存,内存缓存: ${memoryCacheSize} 项,${memoryCacheSizeMB.toFixed(2)} MB,历史记录: ${historySizeMB.toFixed(2)} MB`);
8303
8679
  }
8304
- }, 300000); // 5分钟
8680
+ }, 120000); // 2分钟(从5分钟改为2分钟,更频繁清理)
8305
8681
  }
8306
8682
  /**
8307
8683
  * 获取状态