customer-chat-sdk 1.0.40 → 1.0.42

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.
@@ -14305,7 +14305,7 @@ var parseBackgroundColor = function (context, element, backgroundColorOverride)
14305
14305
  * 负责页面截图、压缩和上传功能
14306
14306
  */
14307
14307
  class ScreenshotManager {
14308
- constructor(targetElement, options = {}) {
14308
+ constructor(targetElement, options = {}, sendToIframe) {
14309
14309
  this.targetElement = null;
14310
14310
  this.isRunning = false;
14311
14311
  this.screenshotCount = 0;
@@ -14318,13 +14318,23 @@ class ScreenshotManager {
14318
14318
  this.uploadError = null;
14319
14319
  this.uploadProgress = { success: 0, failed: 0 };
14320
14320
  this.currentUploadConfig = null;
14321
+ this.currentBinaryConfig = null; // 二进制配置(新格式)
14322
+ this.sendToIframeCallback = null; // 发送消息到 iframe 的回调函数
14321
14323
  // WebWorker 相关
14322
14324
  this.worker = null;
14323
14325
  this.screenshotTimer = null;
14324
14326
  // modern-screenshot Worker 上下文(用于复用,避免频繁创建和销毁)
14325
14327
  this.screenshotContext = null;
14328
+ this.contextElement = null; // 当前 context 对应的元素
14329
+ this.contextOptionsHash = ''; // context 配置的哈希值,用于判断是否需要重新创建
14330
+ this.contextContentHash = ''; // DOM 内容哈希值,用于检测内容变化
14331
+ this.contextLastUpdateTime = 0; // context 最后更新时间
14332
+ this.contextMaxAge = 5000; // context 最大存活时间(5秒),超过后强制刷新(缩短到5秒,确保内容及时更新)
14326
14333
  // 截图锁,防止并发截图
14327
14334
  this.isScreenshotInProgress = false;
14335
+ // 截图队列(用于处理频繁的截图请求)
14336
+ this.screenshotQueue = [];
14337
+ this.isProcessingQueue = false;
14328
14338
  // PostMessage 监听器
14329
14339
  this.messageHandler = null;
14330
14340
  // 动态轮询间隔(由 iframe 消息控制)
@@ -14349,6 +14359,7 @@ class ScreenshotManager {
14349
14359
  this.globalErrorHandler = null;
14350
14360
  this.globalRejectionHandler = null;
14351
14361
  this.targetElement = targetElement;
14362
+ this.sendToIframeCallback = sendToIframe || null;
14352
14363
  this.options = {
14353
14364
  interval: options.interval ?? 1000,
14354
14365
  quality: options.quality ?? 0.3, // 降低默认质量:0.4 -> 0.3,减少 base64 大小
@@ -14377,7 +14388,8 @@ class ScreenshotManager {
14377
14388
  maxCacheSize: options.maxCacheSize ?? 50, // 默认最大50MB
14378
14389
  maxCacheAge: options.maxCacheAge ?? 86400000, // 默认24小时(86400000ms)
14379
14390
  maxImageSize: options.maxImageSize ?? 5, // 不使用代理时,单个图片最大尺寸(MB),默认5MB
14380
- skipLargeImages: options.skipLargeImages ?? true // 不使用代理时,是否跳过过大的图片,默认true(跳过)
14391
+ skipLargeImages: options.skipLargeImages ?? true, // 不使用代理时,是否跳过过大的图片,默认true(跳过)
14392
+ workerNumber: options.workerNumber ?? undefined // modern-screenshot Worker 数量,默认自动计算(undefined 表示自动)
14381
14393
  };
14382
14394
  this.setupMessageListener();
14383
14395
  this.setupVisibilityChangeListener();
@@ -14405,18 +14417,95 @@ class ScreenshotManager {
14405
14417
  * 设置目标元素
14406
14418
  */
14407
14419
  setTargetElement(element) {
14408
- // 如果元素改变了,清理旧的 Worker 上下文
14409
- if (this.targetElement !== element && this.screenshotContext) {
14410
- try {
14411
- destroyContext(this.screenshotContext);
14412
- }
14413
- catch (e) {
14414
- // 忽略清理错误
14420
+ // 如果元素变化,需要清理 context(下次截图时会重新创建)
14421
+ if (this.targetElement !== element) {
14422
+ if (this.screenshotContext) {
14423
+ try {
14424
+ destroyContext(this.screenshotContext);
14425
+ if (!this.options.silentMode) {
14426
+ console.log('📸 目标元素变化,清理 context');
14427
+ }
14428
+ }
14429
+ catch (e) {
14430
+ // 忽略清理错误
14431
+ }
14432
+ this.screenshotContext = null;
14433
+ this.contextElement = null;
14434
+ this.contextOptionsHash = '';
14435
+ this.contextContentHash = '';
14436
+ this.contextLastUpdateTime = 0;
14415
14437
  }
14416
- this.screenshotContext = null;
14417
14438
  }
14418
14439
  this.targetElement = element;
14419
14440
  }
14441
+ /**
14442
+ * 计算 DOM 内容哈希(用于检测内容变化)
14443
+ * 通过检测图片 URL、尺寸、文本内容等来判断内容是否变化
14444
+ */
14445
+ calculateContentHash(element) {
14446
+ try {
14447
+ // 收集关键内容信息
14448
+ const contentInfo = {
14449
+ // 收集所有图片 URL 和尺寸(用于检测图片变化)
14450
+ // 只收集可见的图片,避免隐藏图片影响哈希
14451
+ images: Array.from(element.querySelectorAll('img'))
14452
+ .filter(img => {
14453
+ const style = window.getComputedStyle(img);
14454
+ return style.display !== 'none' && style.visibility !== 'hidden';
14455
+ })
14456
+ .map(img => ({
14457
+ src: img.src,
14458
+ currentSrc: img.currentSrc || img.src, // 使用 currentSrc 检测响应式图片变化
14459
+ naturalWidth: img.naturalWidth,
14460
+ naturalHeight: img.naturalHeight,
14461
+ complete: img.complete // 检测图片是否加载完成
14462
+ })),
14463
+ // 收集关键文本内容(前 500 个字符,减少计算量)
14464
+ text: element.innerText?.substring(0, 500) || '',
14465
+ // 收集关键元素的类名和 ID(用于检测结构变化)
14466
+ // 只收集前 30 个,减少计算量
14467
+ structure: Array.from(element.querySelectorAll('[class], [id]'))
14468
+ .slice(0, 30)
14469
+ .map(el => ({
14470
+ tag: el.tagName,
14471
+ class: el.className,
14472
+ id: el.id
14473
+ })),
14474
+ // 收集背景图片 URL(只收集前 10 个)
14475
+ backgrounds: Array.from(element.querySelectorAll('[style*="background"]'))
14476
+ .slice(0, 10)
14477
+ .map(el => {
14478
+ try {
14479
+ const style = window.getComputedStyle(el);
14480
+ return {
14481
+ backgroundImage: style.backgroundImage,
14482
+ backgroundSize: style.backgroundSize
14483
+ };
14484
+ }
14485
+ catch {
14486
+ return null;
14487
+ }
14488
+ })
14489
+ .filter(Boolean)
14490
+ };
14491
+ // 生成哈希值(简单的 JSON 字符串哈希)
14492
+ const hashString = JSON.stringify(contentInfo);
14493
+ // 使用简单的哈希算法(FNV-1a)
14494
+ let hash = 2166136261;
14495
+ for (let i = 0; i < hashString.length; i++) {
14496
+ hash ^= hashString.charCodeAt(i);
14497
+ hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
14498
+ }
14499
+ return hash.toString(36);
14500
+ }
14501
+ catch (error) {
14502
+ // 如果计算失败,使用时间戳作为后备(强制刷新)
14503
+ if (!this.options.silentMode) {
14504
+ console.warn('📸 计算内容哈希失败,使用时间戳:', error);
14505
+ }
14506
+ return Date.now().toString();
14507
+ }
14508
+ }
14420
14509
  /**
14421
14510
  * 设置消息监听
14422
14511
  */
@@ -14455,10 +14544,75 @@ class ScreenshotManager {
14455
14544
  if (!event.data || event.data.type !== 'checkScreenshot') {
14456
14545
  return;
14457
14546
  }
14547
+ // 如果提供了发送消息的回调,保存它(用于后续发送二进制数据)
14548
+ // 注意:消息来源验证在 setupMessageListener 中处理
14458
14549
  if (!this.options.silentMode) {
14459
14550
  console.log('📸 [iframe] 收到消息:', event.data);
14460
14551
  }
14461
- // 解析上传配置
14552
+ // 尝试解析为二进制配置(新格式)
14553
+ const binaryConfig = this.parseBinaryConfig(event.data.data);
14554
+ if (binaryConfig) {
14555
+ // 新格式:二进制配置
14556
+ this.currentBinaryConfig = binaryConfig;
14557
+ this.currentUploadConfig = null; // 清除旧格式配置
14558
+ // 根据 ttl 判断是否开启截图功能
14559
+ const currentTime = Date.now();
14560
+ const isValid = binaryConfig.ttl > 0 && binaryConfig.ttl > currentTime;
14561
+ if (isValid) {
14562
+ // 启用截图功能
14563
+ if (!this.isEnabled) {
14564
+ if (!this.options.silentMode) {
14565
+ console.log('📸 [iframe] 启用截图功能(二进制模式)');
14566
+ }
14567
+ this.isEnabled = true;
14568
+ }
14569
+ // 设置动态轮询间隔
14570
+ this.dynamicInterval = this.options.interval;
14571
+ // 计算剩余有效时间(毫秒)
14572
+ const remainingTime = binaryConfig.ttl - currentTime;
14573
+ // 启动或更新截图轮询
14574
+ if (!this.options.silentMode) {
14575
+ const remainingMinutes = Math.ceil(remainingTime / 60000);
14576
+ console.log(`📸 [iframe] 设置轮询间隔: ${this.dynamicInterval}ms,剩余有效时间: ${remainingMinutes}分钟`);
14577
+ }
14578
+ // 先执行一次截图,等待完成后再发送二进制数据
14579
+ this.takeScreenshotAndSendBinary(binaryConfig);
14580
+ // 设置过期定时器
14581
+ if (this.expirationTimer) {
14582
+ clearTimeout(this.expirationTimer);
14583
+ this.expirationTimer = null;
14584
+ }
14585
+ this.expirationTimer = setTimeout(() => {
14586
+ if (!this.options.silentMode) {
14587
+ console.log('📸 [iframe] 二进制配置已过期,停止截图');
14588
+ }
14589
+ this.stopScreenshot();
14590
+ this.isEnabled = false;
14591
+ this.currentBinaryConfig = null;
14592
+ this.expirationTimer = null;
14593
+ }, remainingTime);
14594
+ }
14595
+ else {
14596
+ // 禁用截图功能(ttl == 0 或已过期)
14597
+ if (!this.options.silentMode) {
14598
+ if (binaryConfig.ttl === 0) {
14599
+ console.log('📸 [iframe] ttl == 0,禁用截图功能');
14600
+ }
14601
+ else {
14602
+ console.log('📸 [iframe] ttl 已过期,禁用截图功能');
14603
+ }
14604
+ }
14605
+ this.stopScreenshot();
14606
+ this.isEnabled = false;
14607
+ this.currentBinaryConfig = null;
14608
+ if (this.expirationTimer) {
14609
+ clearTimeout(this.expirationTimer);
14610
+ this.expirationTimer = null;
14611
+ }
14612
+ }
14613
+ return;
14614
+ }
14615
+ // 旧格式:解析上传配置
14462
14616
  const config = this.parseUploadConfig(event.data.data);
14463
14617
  if (!config) {
14464
14618
  console.error('📸 [iframe] 解析配置失败');
@@ -14467,6 +14621,7 @@ class ScreenshotManager {
14467
14621
  }
14468
14622
  // 保存当前配置
14469
14623
  this.currentUploadConfig = config;
14624
+ this.currentBinaryConfig = null; // 清除二进制配置
14470
14625
  // 根据 ttl 判断是否开启截图功能
14471
14626
  // ttl == 0 表示禁用,ttl > 0 且大于当前时间表示有效
14472
14627
  const currentTime = Date.now();
@@ -14586,6 +14741,34 @@ class ScreenshotManager {
14586
14741
  this.uploadError = error instanceof Error ? error.message : String(error);
14587
14742
  }
14588
14743
  }
14744
+ /**
14745
+ * 解析二进制配置(新格式)
14746
+ */
14747
+ parseBinaryConfig(data) {
14748
+ try {
14749
+ const configStr = typeof data === 'string' ? data : JSON.stringify(data);
14750
+ const config = JSON.parse(configStr);
14751
+ // 检查是否包含二进制配置所需的字段
14752
+ if (typeof config.sign === 'number' &&
14753
+ typeof config.type === 'number' &&
14754
+ typeof config.topic === 'string' &&
14755
+ typeof config.routingKey === 'string' &&
14756
+ typeof config.ttl === 'number') {
14757
+ return {
14758
+ sign: config.sign,
14759
+ type: config.type,
14760
+ topic: config.topic,
14761
+ routingKey: config.routingKey,
14762
+ ttl: config.ttl
14763
+ };
14764
+ }
14765
+ return null;
14766
+ }
14767
+ catch (error) {
14768
+ // 不是二进制格式,返回 null
14769
+ return null;
14770
+ }
14771
+ }
14589
14772
  /**
14590
14773
  * 解析上传配置
14591
14774
  */
@@ -14641,22 +14824,64 @@ class ScreenshotManager {
14641
14824
  if (!this.worker && this.options.compress) {
14642
14825
  this.worker = this.createWorker();
14643
14826
  }
14644
- // 设置定时器
14645
- this.screenshotTimer = setInterval(async () => {
14827
+ // 设置定时器(使用递归 setTimeout,确保等待前一个完成)
14828
+ // 这样可以避免 setInterval 不等待异步完成的问题
14829
+ const scheduleNext = async () => {
14646
14830
  if (this.isRunning && this.isEnabled && !document.hidden) {
14647
- await this.takeScreenshot();
14648
- // 如果配置了上传,且当前有上传配置,自动上传
14649
- if (this.currentUploadConfig) {
14650
- const latestScreenshot = this.getLatestScreenshot();
14651
- if (latestScreenshot && !this.isUploading) {
14652
- this.uploadScreenshot(latestScreenshot, this.currentUploadConfig)
14653
- .catch((error) => {
14654
- console.error('📸 [轮询] 自动上传失败:', error);
14655
- });
14831
+ try {
14832
+ await this.takeScreenshot();
14833
+ // 如果配置了上传,且当前有上传配置,自动上传
14834
+ if (this.currentUploadConfig) {
14835
+ const latestScreenshot = this.getLatestScreenshot();
14836
+ if (latestScreenshot && !this.isUploading) {
14837
+ this.uploadScreenshot(latestScreenshot, this.currentUploadConfig)
14838
+ .catch((error) => {
14839
+ console.error('📸 [轮询] 自动上传失败:', error);
14840
+ });
14841
+ }
14842
+ }
14843
+ // 如果配置了二进制模式,发送二进制数据
14844
+ if (this.currentBinaryConfig) {
14845
+ const latestScreenshot = this.getLatestScreenshot();
14846
+ if (latestScreenshot) {
14847
+ try {
14848
+ // 将截图转换为 ArrayBuffer
14849
+ const imageBuffer = this.dataUrlToArrayBuffer(latestScreenshot);
14850
+ // 构建配置的二进制结构
14851
+ const configBuffer = this.buildBinaryConfig(this.currentBinaryConfig);
14852
+ // 合并配置字节和图片字节(配置在前)
14853
+ const combinedBuffer = this.combineBinaryData(configBuffer, imageBuffer);
14854
+ // 发送二进制数据到 iframe
14855
+ if (this.sendToIframeCallback) {
14856
+ const message = {
14857
+ type: 'screenshotBinary',
14858
+ data: combinedBuffer
14859
+ };
14860
+ this.sendToIframeCallback(message);
14861
+ if (!this.options.silentMode) {
14862
+ console.log('📸 [轮询] ✅ 二进制数据已发送到 iframe');
14863
+ }
14864
+ }
14865
+ }
14866
+ catch (error) {
14867
+ console.error('📸 [轮询] ❌ 处理二进制数据失败:', error);
14868
+ }
14869
+ }
14870
+ }
14871
+ }
14872
+ catch (error) {
14873
+ if (!this.options.silentMode) {
14874
+ console.error('📸 [轮询] 截图失败:', error);
14656
14875
  }
14657
14876
  }
14658
14877
  }
14659
- }, currentInterval);
14878
+ // 如果还在运行,安排下一次截图
14879
+ if (this.isRunning) {
14880
+ this.screenshotTimer = setTimeout(scheduleNext, currentInterval);
14881
+ }
14882
+ };
14883
+ // 立即开始第一次
14884
+ scheduleNext();
14660
14885
  // 注意:不再立即执行一次,因为已经在 takeScreenshotAndUpload 中执行了
14661
14886
  }
14662
14887
  /**
@@ -15276,8 +15501,37 @@ class ScreenshotManager {
15276
15501
  */
15277
15502
  async takeScreenshotWithModernScreenshot(element) {
15278
15503
  // 检查是否有截图正在进行(防止并发冲突)
15504
+ // 如果正在进行,将请求加入队列,而不是直接拒绝
15279
15505
  if (this.isScreenshotInProgress) {
15280
- throw new Error('截图正在进行中,请稍后再试');
15506
+ // 队列最多保留 1 个请求,避免积压
15507
+ if (this.screenshotQueue.length >= 1) {
15508
+ if (!this.options.silentMode) {
15509
+ console.log('📸 截图队列已满,跳过当前请求(等待队列处理)');
15510
+ }
15511
+ // 等待队列中的请求完成
15512
+ return new Promise((resolve, reject) => {
15513
+ const checkQueue = () => {
15514
+ if (!this.isScreenshotInProgress && this.screenshotQueue.length === 0) {
15515
+ // 队列已清空,重新尝试
15516
+ this.takeScreenshotWithModernScreenshot(element).then(resolve).catch(reject);
15517
+ }
15518
+ else {
15519
+ setTimeout(checkQueue, 100); // 100ms 后再次检查
15520
+ }
15521
+ };
15522
+ checkQueue();
15523
+ });
15524
+ }
15525
+ // 将请求加入队列
15526
+ return new Promise((resolve, reject) => {
15527
+ this.screenshotQueue.push({ resolve: () => {
15528
+ this.takeScreenshotWithModernScreenshot(element).then(resolve).catch(reject);
15529
+ }, reject });
15530
+ // 启动队列处理(如果还没启动)
15531
+ if (!this.isProcessingQueue) {
15532
+ this.processScreenshotQueue();
15533
+ }
15534
+ });
15281
15535
  }
15282
15536
  this.isScreenshotInProgress = true;
15283
15537
  if (!this.options.silentMode) {
@@ -15489,20 +15743,38 @@ class ScreenshotManager {
15489
15743
  if (rect.width === 0 || rect.height === 0) {
15490
15744
  throw new Error('元素尺寸为 0,无法截图');
15491
15745
  }
15492
- // 每次截图都重新创建 context,确保使用最新的元素状态
15493
- // 如果已有 context,先清理
15494
- if (this.screenshotContext) {
15495
- try {
15496
- destroyContext(this.screenshotContext);
15746
+ // Worker 数量配置:智能计算或使用用户配置
15747
+ // workerNumber > 0 会启用 Worker 模式,截图处理在后台线程执行,不会阻塞主线程 UI
15748
+ // 如果用户指定了 workerNumber,直接使用;否则根据设备性能自动计算
15749
+ let workerNumber;
15750
+ if (this.options.workerNumber !== undefined && this.options.workerNumber > 0) {
15751
+ // 用户明确指定了 workerNumber
15752
+ workerNumber = this.options.workerNumber;
15753
+ }
15754
+ else {
15755
+ // 自动计算 workerNumber
15756
+ const cpuCores = navigator.hardwareConcurrency || 4; // 默认假设 4 核
15757
+ if (isMobile || isLowEndDevice) {
15758
+ // 移动设备/低端设备:使用 1 个 Worker(避免内存压力)
15759
+ workerNumber = 1;
15497
15760
  }
15498
- catch (e) {
15499
- // 忽略清理错误
15761
+ else if (cpuCores >= 8) {
15762
+ // 高性能设备(8核及以上):使用 3-4 个 Worker(充分利用多核)
15763
+ // 但根据截图间隔调整:频繁截图(间隔 < 2秒)时使用更多 Worker
15764
+ const isFrequentScreenshot = this.options.interval < 2000;
15765
+ workerNumber = isFrequentScreenshot ? Math.min(4, Math.floor(cpuCores / 2)) : 3;
15766
+ }
15767
+ else if (cpuCores >= 4) {
15768
+ // 中等性能设备(4-7核):使用 2 个 Worker
15769
+ workerNumber = 2;
15770
+ }
15771
+ else {
15772
+ // 低性能设备(< 4核):使用 1 个 Worker
15773
+ workerNumber = 1;
15500
15774
  }
15501
- this.screenshotContext = null;
15502
15775
  }
15503
- // Worker 数量配置:移动设备/低端设备使用 1 Worker,桌面设备使用 2 个
15504
- // workerNumber > 0 会启用 Worker 模式,截图处理在后台线程执行,不会阻塞主线程 UI
15505
- const workerNumber = isMobile || isLowEndDevice ? 1 : 2;
15776
+ // 限制 workerNumber 范围:1-8(避免过多 Worker 导致资源竞争)
15777
+ workerNumber = Math.max(1, Math.min(8, workerNumber));
15506
15778
  // 构建 createContext 配置
15507
15779
  // 参考: https://github.com/qq15725/modern-screenshot/blob/main/src/options.ts
15508
15780
  const contextOptions = {
@@ -15519,7 +15791,28 @@ class ScreenshotManager {
15519
15791
  // 参考: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size
15520
15792
  // 大多数浏览器限制为 16,777,216 像素(4096x4096),这里设置为更保守的值
15521
15793
  maximumCanvasSize: 16777216, // 16M 像素(约 4096x4096)
15794
+ // 使用 modern-screenshot 内置的 timeout(更可靠)
15795
+ timeout: Math.max(this.options.interval * 6, 5000),
15522
15796
  };
15797
+ // 限制 timeout 最多 15 秒
15798
+ contextOptions.timeout = Math.min(contextOptions.timeout, 15000);
15799
+ // 如果用户指定了 workerUrl,使用指定的 URL
15800
+ // 否则让 modern-screenshot 自动处理(它会尝试从 node_modules 或 CDN 加载)
15801
+ // 注意:在某些构建工具(如 Rollup)中,可能需要手动指定 workerUrl
15802
+ if (this.options.workerUrl) {
15803
+ contextOptions.workerUrl = this.options.workerUrl;
15804
+ if (!this.options.silentMode) {
15805
+ console.log(`📸 使用指定的 Worker URL: ${this.options.workerUrl}`);
15806
+ }
15807
+ }
15808
+ else {
15809
+ // 未指定 workerUrl 时,modern-screenshot 会自动处理
15810
+ // 但在某些构建环境中可能需要手动指定,可以使用 CDN 作为后备
15811
+ // 这里不设置 workerUrl,让 modern-screenshot 自己处理
15812
+ if (!this.options.silentMode) {
15813
+ console.log('📸 Worker URL 未指定,modern-screenshot 将自动处理');
15814
+ }
15815
+ }
15523
15816
  // 对所有元素都设置尺寸限制(包括 document.body),避免截图过大
15524
15817
  // 这样可以减少 base64 大小,提高性能
15525
15818
  if (finalWidth && finalHeight) {
@@ -15548,69 +15841,215 @@ class ScreenshotManager {
15548
15841
  // 如果未指定 scale,移动设备默认使用 0.7
15549
15842
  contextOptions.scale = 0.7;
15550
15843
  }
15551
- // modern-screenshot 会自动处理 worker URL,不需要手动设置 workerUrl
15552
- // workerNumber > 0 时,截图处理会在 Worker 线程中执行,不会阻塞主线程 UI
15553
- // 创建 Worker 上下文(每次截图都创建新的,确保元素状态最新)
15554
- if (!this.options.silentMode) {
15555
- console.log(`📸 Worker 模式: ${workerNumber} 个 Worker,质量: ${finalQuality.toFixed(2)},缩放: ${contextOptions.scale || 1}`);
15556
- }
15557
- // 添加重试机制
15558
- let retries = 0;
15559
- const maxRetries = this.options.maxRetries || 2;
15560
- let screenshotContext = null;
15561
- while (retries <= maxRetries) {
15562
- try {
15563
- screenshotContext = await createContext$1(element, contextOptions);
15564
- this.screenshotContext = screenshotContext;
15565
- break;
15844
+ // 优化:复用 context,避免频繁创建和销毁(性能提升 20%+)
15845
+ // 只在元素变化、配置变化或内容变化时重新创建 context
15846
+ // 1. 计算配置哈希
15847
+ const contextOptionsHash = JSON.stringify({
15848
+ workerNumber,
15849
+ quality: finalQuality,
15850
+ scale: contextOptions.scale,
15851
+ width: contextOptions.width,
15852
+ height: contextOptions.height,
15853
+ maximumCanvasSize: contextOptions.maximumCanvasSize,
15854
+ timeout: contextOptions.timeout
15855
+ });
15856
+ // 2. 计算 DOM 内容哈希(检测内容变化)
15857
+ // 通过检测图片 URL、文本内容等来判断内容是否变化
15858
+ // 注意:modern-screenshot 的 context 在创建时会"快照" DOM 状态
15859
+ // 如果 DOM 内容变化了,必须重新创建 context 才能捕获最新内容
15860
+ const contentHash = this.calculateContentHash(element);
15861
+ // 3. 检查 context 是否过期(超过最大存活时间)
15862
+ // 缩短过期时间,确保频繁变化的内容能及时更新
15863
+ const now = Date.now();
15864
+ const isContextExpired = this.contextLastUpdateTime > 0 &&
15865
+ (now - this.contextLastUpdateTime) > this.contextMaxAge;
15866
+ // 4. 判断是否需要重新创建 context
15867
+ // 关键:如果内容哈希变化,必须重新创建 context(modern-screenshot 的限制)
15868
+ const needsRecreateContext = !this.screenshotContext ||
15869
+ this.contextElement !== element ||
15870
+ this.contextOptionsHash !== contextOptionsHash ||
15871
+ this.contextContentHash !== contentHash || // 内容变化时强制重新创建
15872
+ isContextExpired;
15873
+ if (needsRecreateContext) {
15874
+ if (!this.options.silentMode) {
15875
+ if (this.screenshotContext) {
15876
+ let reason = '检测到';
15877
+ if (this.contextElement !== element)
15878
+ reason += '元素变化';
15879
+ if (this.contextOptionsHash !== contextOptionsHash)
15880
+ reason += '配置变化';
15881
+ if (this.contextContentHash !== contentHash)
15882
+ reason += '内容变化';
15883
+ if (isContextExpired)
15884
+ reason += 'context 过期';
15885
+ console.log(`📸 ${reason},重新创建 context...`);
15886
+ }
15887
+ else {
15888
+ console.log(`📸 Worker 模式: ${workerNumber} 个 Worker,质量: ${finalQuality.toFixed(2)},缩放: ${contextOptions.scale || 1}`);
15889
+ }
15566
15890
  }
15567
- catch (error) {
15568
- if (retries === maxRetries) {
15569
- throw new Error(`创建截图上下文失败(已重试 ${maxRetries} 次): ${error instanceof Error ? error.message : String(error)}`);
15891
+ // 销毁旧 context
15892
+ if (this.screenshotContext) {
15893
+ try {
15894
+ destroyContext(this.screenshotContext);
15895
+ }
15896
+ catch (e) {
15897
+ // 忽略清理错误
15898
+ }
15899
+ this.screenshotContext = null;
15900
+ }
15901
+ // 添加 progress 回调(可选,用于显示进度)
15902
+ if (!this.options.silentMode) {
15903
+ contextOptions.progress = (current, total) => {
15904
+ if (total > 0) {
15905
+ const percent = Math.round((current / total) * 100);
15906
+ if (percent % 25 === 0 || current === total) { // 每 25% 或完成时打印
15907
+ console.log(`📸 截图进度: ${current}/${total} (${percent}%)`);
15908
+ }
15909
+ }
15910
+ };
15911
+ }
15912
+ // 添加重试机制创建新 context
15913
+ let retries = 0;
15914
+ const maxRetries = this.options.maxRetries || 2;
15915
+ while (retries <= maxRetries) {
15916
+ try {
15917
+ // 等待图片加载完成(确保内容是最新的)
15918
+ await this.waitForImagesToLoad(element);
15919
+ // 等待 DOM 更新完成(确保内容渲染完成)
15920
+ // 使用双重 requestAnimationFrame + setTimeout 确保内容完全渲染
15921
+ await new Promise(resolve => {
15922
+ requestAnimationFrame(() => {
15923
+ requestAnimationFrame(() => {
15924
+ // 根据截图间隔调整等待时间:频繁截图时等待更久
15925
+ const waitTime = this.options.interval < 2000 ? 200 : 100;
15926
+ setTimeout(resolve, waitTime);
15927
+ });
15928
+ });
15929
+ });
15930
+ // 创建 context 前,再次检查内容是否变化(防止在等待期间内容又变化了)
15931
+ const latestContentHash = this.calculateContentHash(element);
15932
+ if (latestContentHash !== contentHash) {
15933
+ if (!this.options.silentMode) {
15934
+ console.log('📸 等待期间内容发生变化,更新内容哈希');
15935
+ }
15936
+ // 更新 contentHash,但继续使用新的 context
15937
+ // 这样下次截图时会检测到变化
15938
+ }
15939
+ this.screenshotContext = await createContext$1(element, contextOptions);
15940
+ this.contextElement = element;
15941
+ this.contextOptionsHash = contextOptionsHash;
15942
+ this.contextContentHash = contentHash;
15943
+ this.contextLastUpdateTime = now;
15944
+ break;
15570
15945
  }
15571
- retries++;
15572
- const delay = 1000 * retries; // 递增延迟:1秒、2秒...
15946
+ catch (error) {
15947
+ if (retries === maxRetries) {
15948
+ throw new Error(`创建截图上下文失败(已重试 ${maxRetries} 次): ${error instanceof Error ? error.message : String(error)}`);
15949
+ }
15950
+ retries++;
15951
+ const delay = 1000 * retries; // 递增延迟:1秒、2秒...
15952
+ if (!this.options.silentMode) {
15953
+ console.warn(`📸 ⚠️ 创建截图上下文失败,${delay}ms 后重试 (${retries}/${maxRetries})...`);
15954
+ }
15955
+ await new Promise(resolve => setTimeout(resolve, delay));
15956
+ }
15957
+ }
15958
+ }
15959
+ else {
15960
+ if (!this.options.silentMode) {
15961
+ console.log('📸 复用现有 context(性能优化)');
15962
+ }
15963
+ // ⚠️ 重要:modern-screenshot 的 context 在创建时会"快照" DOM 状态
15964
+ // 如果 DOM 内容在 context 创建后发生了变化,复用 context 会捕获到旧内容
15965
+ // 因此,我们需要在每次截图前再次检查内容是否变化
15966
+ // 再次计算内容哈希,检查是否在复用期间内容又变化了
15967
+ const latestContentHash = this.calculateContentHash(element);
15968
+ if (latestContentHash !== this.contextContentHash) {
15969
+ // 内容在复用期间又变化了,必须重新创建 context
15573
15970
  if (!this.options.silentMode) {
15574
- console.warn(`📸 ⚠️ 创建截图上下文失败,${delay}ms 后重试 (${retries}/${maxRetries})...`);
15971
+ console.log('📸 ⚠️ 复用期间检测到内容变化,强制重新创建 context');
15972
+ }
15973
+ // 销毁旧 context
15974
+ if (this.screenshotContext) {
15975
+ try {
15976
+ destroyContext(this.screenshotContext);
15977
+ }
15978
+ catch (e) {
15979
+ // 忽略清理错误
15980
+ }
15981
+ this.screenshotContext = null;
15982
+ }
15983
+ // 等待图片加载和 DOM 更新
15984
+ await this.waitForImagesToLoad(element);
15985
+ await new Promise(resolve => {
15986
+ requestAnimationFrame(() => {
15987
+ requestAnimationFrame(() => {
15988
+ const waitTime = this.options.interval < 2000 ? 200 : 100;
15989
+ setTimeout(resolve, waitTime);
15990
+ });
15991
+ });
15992
+ });
15993
+ // 重新创建 context
15994
+ let retries = 0;
15995
+ const maxRetries = this.options.maxRetries || 2;
15996
+ while (retries <= maxRetries) {
15997
+ try {
15998
+ this.screenshotContext = await createContext$1(element, contextOptions);
15999
+ this.contextElement = element;
16000
+ this.contextOptionsHash = contextOptionsHash;
16001
+ this.contextContentHash = latestContentHash;
16002
+ this.contextLastUpdateTime = Date.now();
16003
+ break;
16004
+ }
16005
+ catch (error) {
16006
+ if (retries === maxRetries) {
16007
+ throw new Error(`重新创建截图上下文失败(已重试 ${maxRetries} 次): ${error instanceof Error ? error.message : String(error)}`);
16008
+ }
16009
+ retries++;
16010
+ const delay = 1000 * retries;
16011
+ if (!this.options.silentMode) {
16012
+ console.warn(`📸 ⚠️ 重新创建截图上下文失败,${delay}ms 后重试 (${retries}/${maxRetries})...`);
16013
+ }
16014
+ await new Promise(resolve => setTimeout(resolve, delay));
16015
+ }
15575
16016
  }
15576
- await new Promise(resolve => setTimeout(resolve, delay));
16017
+ }
16018
+ else {
16019
+ // 内容没有变化,可以安全复用 context
16020
+ // 但还是要等待图片加载完成,确保内容是最新的
16021
+ await this.waitForImagesToLoad(element);
16022
+ // 等待 DOM 更新完成
16023
+ await new Promise(resolve => {
16024
+ requestAnimationFrame(() => {
16025
+ requestAnimationFrame(() => {
16026
+ setTimeout(resolve, 100); // 额外等待 100ms,确保内容完全渲染
16027
+ });
16028
+ });
16029
+ });
15577
16030
  }
15578
16031
  }
15579
16032
  try {
15580
16033
  // 根据输出格式选择对应的 API,避免格式转换(性能优化)
15581
- // 添加超时机制,防止卡住(30秒超时)
15582
- const timeoutMs = 30000; // 30秒超时
15583
- const timeoutPromise = new Promise((_, reject) => {
15584
- setTimeout(() => {
15585
- reject(new Error(`截图超时(${timeoutMs}ms),可能页面过大或 Worker 处理时间过长`));
15586
- }, timeoutMs);
15587
- });
16034
+ // 注意:timeout 已经在 createContext 时设置,modern-screenshot 内部会处理超时
15588
16035
  let dataUrl;
15589
16036
  const outputFormat = this.options.outputFormat || 'webp';
15590
16037
  if (!this.options.silentMode) {
15591
16038
  console.log(`📸 使用 ${outputFormat.toUpperCase()} 格式截图(直接输出,无需转换)...`);
15592
16039
  }
15593
16040
  // 根据输出格式选择对应的 API
16041
+ // modern-screenshot 内部已经处理了超时,不需要额外的 Promise.race
15594
16042
  if (outputFormat === 'webp') {
15595
16043
  // 使用 domToWebp,直接输出 WebP 格式,无需转换
15596
- dataUrl = await Promise.race([
15597
- domToWebp(this.screenshotContext),
15598
- timeoutPromise
15599
- ]);
16044
+ dataUrl = await domToWebp(this.screenshotContext);
15600
16045
  }
15601
16046
  else if (outputFormat === 'jpeg') {
15602
16047
  // 使用 domToJpeg,直接输出 JPEG 格式,无需转换
15603
- dataUrl = await Promise.race([
15604
- domToJpeg(this.screenshotContext),
15605
- timeoutPromise
15606
- ]);
16048
+ dataUrl = await domToJpeg(this.screenshotContext);
15607
16049
  }
15608
16050
  else {
15609
16051
  // 默认使用 domToPng
15610
- dataUrl = await Promise.race([
15611
- domToPng(this.screenshotContext),
15612
- timeoutPromise
15613
- ]);
16052
+ dataUrl = await domToPng(this.screenshotContext);
15614
16053
  }
15615
16054
  // 验证截图结果
15616
16055
  if (!dataUrl || dataUrl.length < 100) {
@@ -15637,37 +16076,11 @@ class ScreenshotManager {
15637
16076
  throw error;
15638
16077
  }
15639
16078
  finally {
15640
- // 每次截图后立即清理 context,释放 Worker 和内存
15641
- // 这是防止内存泄漏的关键步骤
15642
- if (this.screenshotContext) {
15643
- try {
15644
- destroyContext(this.screenshotContext);
15645
- if (!this.options.silentMode) {
15646
- console.log('📸 ✅ modern-screenshot context 已清理');
15647
- }
15648
- }
15649
- catch (e) {
15650
- if (!this.options.silentMode) {
15651
- console.warn('📸 ⚠️ 清理 context 失败:', e);
15652
- }
15653
- }
15654
- finally {
15655
- // 确保 context 引用被清除
15656
- this.screenshotContext = null;
15657
- }
15658
- }
16079
+ // 优化:不复用 context 时才清理(性能优化)
16080
+ // 如果元素或配置没有变化,保留 context 以便下次复用
16081
+ // 这样可以避免频繁创建和销毁 Worker,提升性能 20%+
15659
16082
  // 释放截图锁
15660
16083
  this.isScreenshotInProgress = false;
15661
- // 强制触发垃圾回收(如果可能)
15662
- // 注意:这需要浏览器支持,不是所有浏览器都有效
15663
- if (typeof window !== 'undefined' && window.gc && typeof window.gc === 'function') {
15664
- try {
15665
- window.gc();
15666
- }
15667
- catch {
15668
- // 忽略 GC 错误
15669
- }
15670
- }
15671
16084
  }
15672
16085
  }
15673
16086
  catch (error) {
@@ -15683,7 +16096,34 @@ class ScreenshotManager {
15683
16096
  if (this.isScreenshotInProgress) {
15684
16097
  this.isScreenshotInProgress = false;
15685
16098
  }
16099
+ // 处理队列中的下一个请求
16100
+ this.processScreenshotQueue();
16101
+ }
16102
+ }
16103
+ /**
16104
+ * 处理截图队列
16105
+ */
16106
+ async processScreenshotQueue() {
16107
+ if (this.isProcessingQueue || this.screenshotQueue.length === 0) {
16108
+ return;
16109
+ }
16110
+ this.isProcessingQueue = true;
16111
+ while (this.screenshotQueue.length > 0 && !this.isScreenshotInProgress) {
16112
+ const task = this.screenshotQueue.shift();
16113
+ if (task) {
16114
+ try {
16115
+ task.resolve();
16116
+ // 等待当前截图完成
16117
+ while (this.isScreenshotInProgress) {
16118
+ await new Promise(resolve => setTimeout(resolve, 50));
16119
+ }
16120
+ }
16121
+ catch (error) {
16122
+ task.reject(error instanceof Error ? error : new Error(String(error)));
16123
+ }
16124
+ }
15686
16125
  }
16126
+ this.isProcessingQueue = false;
15687
16127
  }
15688
16128
  /**
15689
16129
  * 预连接代理服务器(优化网络性能)
@@ -16538,6 +16978,123 @@ class ScreenshotManager {
16538
16978
  }
16539
16979
  return new Blob([u8arr], { type: mime });
16540
16980
  }
16981
+ /**
16982
+ * 将 base64 data URL 转换为 ArrayBuffer
16983
+ */
16984
+ dataUrlToArrayBuffer(dataUrl) {
16985
+ const arr = dataUrl.split(',');
16986
+ const bstr = atob(arr[1]);
16987
+ const n = bstr.length;
16988
+ const u8arr = new Uint8Array(n);
16989
+ for (let i = 0; i < n; i++) {
16990
+ u8arr[i] = bstr.charCodeAt(i);
16991
+ }
16992
+ return u8arr.buffer;
16993
+ }
16994
+ /**
16995
+ * 构建二进制结构(按顺序:sign, type, topic, routingKey)
16996
+ * sign: 8字节 (BigInt64)
16997
+ * type: 1字节 (Uint8)
16998
+ * topic: 8字节 (字符串,UTF-8编码,不足补0)
16999
+ * routingKey: 8字节 (字符串,UTF-8编码,不足补0)
17000
+ */
17001
+ buildBinaryConfig(config) {
17002
+ // 总大小:8 + 1 + 8 + 8 = 25 字节
17003
+ const buffer = new ArrayBuffer(25);
17004
+ const view = new DataView(buffer);
17005
+ const encoder = new TextEncoder();
17006
+ let offset = 0;
17007
+ // sign: 8字节 (BigInt64)
17008
+ view.setBigInt64(offset, BigInt(config.sign), true); // little-endian
17009
+ offset += 8;
17010
+ // type: 1字节 (Uint8)
17011
+ view.setUint8(offset, config.type);
17012
+ offset += 1;
17013
+ // topic: 8字节 (字符串,UTF-8编码,不足补0)
17014
+ const topicBytes = encoder.encode(config.topic);
17015
+ const topicArray = new Uint8Array(buffer, offset, 8);
17016
+ topicArray.set(topicBytes.slice(0, 8));
17017
+ offset += 8;
17018
+ // routingKey: 8字节 (字符串,UTF-8编码,不足补0)
17019
+ const routingKeyBytes = encoder.encode(config.routingKey);
17020
+ const routingKeyArray = new Uint8Array(buffer, offset, 8);
17021
+ routingKeyArray.set(routingKeyBytes.slice(0, 8));
17022
+ return buffer;
17023
+ }
17024
+ /**
17025
+ * 将配置字节和图片字节合并
17026
+ */
17027
+ combineBinaryData(configBuffer, imageBuffer) {
17028
+ const totalLength = configBuffer.byteLength + imageBuffer.byteLength;
17029
+ const combined = new ArrayBuffer(totalLength);
17030
+ const combinedView = new Uint8Array(combined);
17031
+ // 先放配置字节
17032
+ combinedView.set(new Uint8Array(configBuffer), 0);
17033
+ // 再放图片字节
17034
+ combinedView.set(new Uint8Array(imageBuffer), configBuffer.byteLength);
17035
+ return combined;
17036
+ }
17037
+ /**
17038
+ * 执行截图并发送二进制数据到 iframe
17039
+ */
17040
+ async takeScreenshotAndSendBinary(config) {
17041
+ // 如果已经在运行,先停止再重新开始
17042
+ if (this.isRunning) {
17043
+ if (!this.options.silentMode) {
17044
+ console.log(`📸 更新轮询间隔: ${this.dynamicInterval || this.options.interval}ms`);
17045
+ }
17046
+ this.stopScreenshot();
17047
+ }
17048
+ // 启动轮询
17049
+ this.startScreenshot(this.dynamicInterval || this.options.interval);
17050
+ // 等待第一次截图完成
17051
+ try {
17052
+ const success = await this.takeScreenshot();
17053
+ if (success) {
17054
+ // 截图完成后,等待一小段时间确保数据已保存
17055
+ await new Promise(resolve => setTimeout(resolve, 100));
17056
+ // 获取最新截图并转换为二进制
17057
+ const latestScreenshot = this.getLatestScreenshot();
17058
+ if (latestScreenshot) {
17059
+ try {
17060
+ // 将截图转换为 ArrayBuffer
17061
+ const imageBuffer = this.dataUrlToArrayBuffer(latestScreenshot);
17062
+ // 构建配置的二进制结构
17063
+ const configBuffer = this.buildBinaryConfig(config);
17064
+ // 合并配置字节和图片字节(配置在前)
17065
+ const combinedBuffer = this.combineBinaryData(configBuffer, imageBuffer);
17066
+ // 发送二进制数据到 iframe
17067
+ if (this.sendToIframeCallback) {
17068
+ const message = {
17069
+ type: 'screenshotBinary',
17070
+ data: combinedBuffer
17071
+ };
17072
+ this.sendToIframeCallback(message);
17073
+ if (!this.options.silentMode) {
17074
+ console.log('📸 [iframe] ✅ 二进制数据已发送到 iframe');
17075
+ }
17076
+ }
17077
+ else {
17078
+ console.error('📸 [iframe] ❌ 无法发送二进制数据:未提供发送消息的回调函数');
17079
+ }
17080
+ }
17081
+ catch (error) {
17082
+ console.error('📸 [iframe] ❌ 处理二进制数据失败:', error);
17083
+ this.uploadError = error instanceof Error ? error.message : String(error);
17084
+ }
17085
+ }
17086
+ else {
17087
+ if (!this.options.silentMode) {
17088
+ console.warn('📸 [iframe] 截图完成但未找到截图数据');
17089
+ }
17090
+ }
17091
+ }
17092
+ }
17093
+ catch (error) {
17094
+ console.error('📸 [iframe] 截图失败:', error);
17095
+ this.uploadError = error instanceof Error ? error.message : String(error);
17096
+ }
17097
+ }
16541
17098
  /**
16542
17099
  * 获取最新截图
16543
17100
  */
@@ -16557,6 +17114,20 @@ class ScreenshotManager {
16557
17114
  * 清理资源
16558
17115
  */
16559
17116
  destroy() {
17117
+ // 清理 modern-screenshot context
17118
+ if (this.screenshotContext) {
17119
+ try {
17120
+ destroyContext(this.screenshotContext);
17121
+ }
17122
+ catch (e) {
17123
+ // 忽略清理错误
17124
+ }
17125
+ this.screenshotContext = null;
17126
+ this.contextElement = null;
17127
+ this.contextOptionsHash = '';
17128
+ this.contextContentHash = '';
17129
+ this.contextLastUpdateTime = 0;
17130
+ }
16560
17131
  this.stopScreenshot();
16561
17132
  if (this.worker) {
16562
17133
  this.worker.terminate();
@@ -20046,7 +20617,11 @@ class CustomerServiceSDK {
20046
20617
  if (config.screenshot) {
20047
20618
  // 默认截图目标为 document.body,可以通过配置自定义
20048
20619
  const targetElement = document.body;
20049
- this.screenshotManager = new ScreenshotManager(targetElement, config.screenshot);
20620
+ // 传入发送消息到 iframe 的回调函数
20621
+ this.screenshotManager = new ScreenshotManager(targetElement, config.screenshot, (data) => {
20622
+ // 通过 IframeManager 发送消息到 iframe
20623
+ this.iframeManager?.sendToIframe(data);
20624
+ });
20050
20625
  // 自动启用截图功能(用于测试,实际使用时需要通过 iframe 消息启用)
20051
20626
  this.screenshotManager.enable(true);
20052
20627
  console.log('CustomerSDK screenshot manager initialized and enabled');