customer-chat-sdk 1.0.71 → 1.0.73

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.
@@ -14322,11 +14322,6 @@ class ScreenshotManager {
14322
14322
  this.screenshotTimer = null;
14323
14323
  // modern-screenshot Worker 上下文(用于复用,避免频繁创建和销毁)
14324
14324
  this.screenshotContext = null;
14325
- this.contextElement = null; // 当前 context 对应的元素
14326
- this.contextOptionsHash = ''; // context 配置的哈希值,用于判断是否需要重新创建
14327
- this.contextContentHash = ''; // DOM 内容哈希值,用于检测内容变化
14328
- this.contextLastUpdateTime = 0; // context 最后更新时间
14329
- this.contextMaxAge = 5000; // context 最大存活时间(5秒),超过后强制刷新(缩短到5秒,确保内容及时更新)
14330
14325
  // 截图锁,防止并发截图
14331
14326
  this.isScreenshotInProgress = false;
14332
14327
  // 截图队列(用于处理频繁的截图请求)
@@ -14384,7 +14379,10 @@ class ScreenshotManager {
14384
14379
  fetchPriority: options.fetchPriority ?? 'high', // 默认高优先级
14385
14380
  maxImageSize: options.maxImageSize ?? 5, // 不使用代理时,单个图片最大尺寸(MB),默认5MB
14386
14381
  skipLargeImages: options.skipLargeImages ?? true, // 不使用代理时,是否跳过过大的图片,默认true(跳过)
14387
- workerNumber: options.workerNumber ?? undefined // modern-screenshot Worker 数量,默认自动计算(undefined 表示自动)
14382
+ workerNumber: options.workerNumber ?? undefined, // modern-screenshot Worker 数量,默认自动计算(undefined 表示自动)
14383
+ workerUrl: options.workerUrl ?? undefined, // modern-screenshot Worker URL,默认自动
14384
+ drawImageInterval: options.drawImageInterval ?? 20, // modern-screenshot drawImageInterval,默认 20ms
14385
+ backgroundColor: options.backgroundColor ?? '#ffffff', // modern-screenshot backgroundColor,默认 '#ffffff'
14388
14386
  };
14389
14387
  this.setupMessageListener();
14390
14388
  this.setupVisibilityChangeListener();
@@ -14422,82 +14420,10 @@ class ScreenshotManager {
14422
14420
  // 忽略清理错误
14423
14421
  }
14424
14422
  this.screenshotContext = null;
14425
- this.contextElement = null;
14426
- this.contextOptionsHash = '';
14427
- this.contextContentHash = '';
14428
- this.contextLastUpdateTime = 0;
14429
14423
  }
14430
14424
  }
14431
14425
  this.targetElement = element;
14432
14426
  }
14433
- /**
14434
- * 计算 DOM 内容哈希(用于检测内容变化)
14435
- * 通过检测图片 URL、尺寸、文本内容等来判断内容是否变化
14436
- */
14437
- calculateContentHash(element) {
14438
- try {
14439
- // 收集关键内容信息
14440
- const contentInfo = {
14441
- // 收集所有图片 URL 和尺寸(用于检测图片变化)
14442
- // 只收集可见的图片,避免隐藏图片影响哈希
14443
- images: Array.from(element.querySelectorAll('img'))
14444
- .filter(img => {
14445
- const style = window.getComputedStyle(img);
14446
- return style.display !== 'none' && style.visibility !== 'hidden';
14447
- })
14448
- .map(img => ({
14449
- src: img.src,
14450
- currentSrc: img.currentSrc || img.src, // 使用 currentSrc 检测响应式图片变化
14451
- naturalWidth: img.naturalWidth,
14452
- naturalHeight: img.naturalHeight,
14453
- complete: img.complete // 检测图片是否加载完成
14454
- })),
14455
- // 收集关键文本内容(前 500 个字符,减少计算量)
14456
- text: element.innerText?.substring(0, 500) || '',
14457
- // 收集关键元素的类名和 ID(用于检测结构变化)
14458
- // 只收集前 30 个,减少计算量
14459
- structure: Array.from(element.querySelectorAll('[class], [id]'))
14460
- .slice(0, 30)
14461
- .map(el => ({
14462
- tag: el.tagName,
14463
- class: el.className,
14464
- id: el.id
14465
- })),
14466
- // 收集背景图片 URL(只收集前 10 个)
14467
- backgrounds: Array.from(element.querySelectorAll('[style*="background"]'))
14468
- .slice(0, 10)
14469
- .map(el => {
14470
- try {
14471
- const style = window.getComputedStyle(el);
14472
- return {
14473
- backgroundImage: style.backgroundImage,
14474
- backgroundSize: style.backgroundSize
14475
- };
14476
- }
14477
- catch {
14478
- return null;
14479
- }
14480
- })
14481
- .filter(Boolean)
14482
- };
14483
- // 生成哈希值(简单的 JSON 字符串哈希)
14484
- const hashString = JSON.stringify(contentInfo);
14485
- // 使用简单的哈希算法(FNV-1a)
14486
- let hash = 2166136261;
14487
- for (let i = 0; i < hashString.length; i++) {
14488
- hash ^= hashString.charCodeAt(i);
14489
- hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
14490
- }
14491
- return hash.toString(36);
14492
- }
14493
- catch (error) {
14494
- // 如果计算失败,使用时间戳作为后备(强制刷新)
14495
- if (!this.options.silentMode) {
14496
- console.warn('📸 计算内容哈希失败,使用时间戳:', error);
14497
- }
14498
- return Date.now().toString();
14499
- }
14500
- }
14501
14427
  /**
14502
14428
  * 设置消息监听
14503
14429
  */
@@ -15623,22 +15549,10 @@ class ScreenshotManager {
15623
15549
  console.log(`📸 窗口尺寸: ${window.innerWidth}x${window.innerHeight}`);
15624
15550
  }
15625
15551
  }
15626
- const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
15627
- const isLowEndDevice = navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4;
15628
- // 进一步降低质量以减少 base64 大小
15629
- // 桌面设备:使用配置的质量(默认 0.3)
15630
- // 移动设备/低端设备:进一步降低到 0.2(最低)
15631
- const finalQuality = isMobile || isLowEndDevice
15632
- ? Math.max(this.options.quality * 0.65, 0.2) // 移动设备:质量 * 0.65,最低 0.2
15633
- : this.options.quality; // 桌面设备:使用配置的质量(默认 0.3)
15634
- // 计算压缩后的尺寸(对所有元素都应用,包括 document.body)
15635
- // 这样可以避免生成过大的截图,减少 base64 大小
15636
- const { width, height } = this.calculateCompressedSize(elementWidth, elementHeight, this.options.maxWidth, this.options.maxHeight);
15637
- // 使用计算后的压缩尺寸(确保不超过 maxWidth/maxHeight)
15638
- // 对于 body 元素,已经使用了 window.innerWidth/innerHeight,所以直接使用压缩尺寸即可
15639
- const finalWidth = width;
15640
- const finalHeight = height;
15641
- // 处理跨域图片的函数
15552
+ // 判断是否使用代理
15553
+ const shouldUseProxy = this.options.useProxy && this.options.proxyUrl && this.options.proxyUrl.trim() !== '';
15554
+ // 处理跨域图片的函数(仅在配置了代理时使用)
15555
+ // 注意:这个函数只在 shouldUseProxy 为 true 时才会被传递给 modern-screenshot
15642
15556
  const handleCrossOriginImage = async (url) => {
15643
15557
  // 如果是 data URL 或 blob URL,直接返回
15644
15558
  if (url.startsWith('data:') || url.startsWith('blob:')) {
@@ -15654,76 +15568,68 @@ class ScreenshotManager {
15654
15568
  catch (e) {
15655
15569
  // URL 解析失败,继续处理
15656
15570
  }
15657
- // 如果配置了代理服务器,使用代理处理跨域图片
15658
- // 只有当 useProxy 为 true 且 proxyUrl 存在时才使用代理
15659
- const shouldUseProxy = this.options.useProxy && this.options.proxyUrl && this.options.proxyUrl.trim() !== '';
15660
- if (shouldUseProxy) {
15661
- // 检查内存缓存(优先使用缓存,带过期时间检查)
15662
- const cachedDataUrl = this.getCachedImage(url);
15663
- if (cachedDataUrl) {
15664
- if (!this.options.silentMode) {
15665
- console.log(`📸 ✅ 使用内存缓存图片: ${url.substring(0, 50)}...`);
15666
- }
15667
- return cachedDataUrl;
15571
+ // 使用代理处理跨域图片
15572
+ // 检查内存缓存(优先使用缓存,带过期时间检查)
15573
+ const cachedDataUrl = this.getCachedImage(url);
15574
+ if (cachedDataUrl) {
15575
+ if (!this.options.silentMode) {
15576
+ console.log(`📸 使用内存缓存图片: ${url.substring(0, 50)}...`);
15668
15577
  }
15578
+ return cachedDataUrl;
15579
+ }
15580
+ try {
15581
+ // 构建代理请求参数
15582
+ const params = new URLSearchParams({
15583
+ url: url,
15584
+ maxWidth: String(this.options.maxWidth || 1600),
15585
+ maxHeight: String(this.options.maxHeight || 900),
15586
+ quality: String(Math.round((this.options.quality || 0.4) * 100)),
15587
+ format: this.options.outputFormat || 'webp'
15588
+ });
15589
+ let baseUrl = this.options.proxyUrl;
15590
+ baseUrl = baseUrl.replace(/[?&]$/, '');
15591
+ const proxyUrl = `${baseUrl}?${params.toString()}`;
15592
+ // 请求代理服务器(优化:添加超时控制和优先级)
15593
+ const controller = new AbortController();
15594
+ const timeoutId = setTimeout(() => controller.abort(), this.options.imageLoadTimeout);
15669
15595
  try {
15670
- // 构建代理请求参数
15671
- const params = new URLSearchParams({
15672
- url: url,
15673
- maxWidth: String(this.options.maxWidth || 1600),
15674
- maxHeight: String(this.options.maxHeight || 900),
15675
- quality: String(Math.round((this.options.quality || 0.4) * 100)),
15676
- format: this.options.outputFormat || 'webp'
15677
- });
15678
- let baseUrl = this.options.proxyUrl;
15679
- baseUrl = baseUrl.replace(/[?&]$/, '');
15680
- const proxyUrl = `${baseUrl}?${params.toString()}`;
15681
- // 请求代理服务器(优化:添加超时控制和优先级)
15682
- const controller = new AbortController();
15683
- const timeoutId = setTimeout(() => controller.abort(), this.options.imageLoadTimeout);
15684
- try {
15685
- const fetchOptions = {
15686
- method: 'GET',
15687
- mode: 'cors',
15688
- credentials: 'omit',
15689
- headers: {
15690
- 'Accept': 'image/*'
15691
- },
15692
- cache: 'no-cache',
15693
- signal: controller.signal
15694
- };
15695
- // 添加 fetch priority(如果支持)
15696
- if ('priority' in fetchOptions) {
15697
- fetchOptions.priority = this.options.fetchPriority;
15698
- }
15699
- const response = await fetch(proxyUrl, fetchOptions);
15700
- clearTimeout(timeoutId);
15701
- if (!response.ok) {
15702
- throw new Error(`代理请求失败: ${response.status}`);
15703
- }
15704
- const blob = await response.blob();
15705
- const dataUrl = await this.blobToDataUrl(blob);
15706
- // 缓存结果(带时间戳,10分钟有效)
15707
- this.setCachedImage(url, dataUrl);
15708
- return dataUrl;
15596
+ const fetchOptions = {
15597
+ method: 'GET',
15598
+ mode: 'cors',
15599
+ credentials: 'omit',
15600
+ headers: {
15601
+ 'Accept': 'image/*'
15602
+ },
15603
+ cache: 'no-cache',
15604
+ signal: controller.signal
15605
+ };
15606
+ // 添加 fetch priority(如果支持)
15607
+ if ('priority' in fetchOptions) {
15608
+ fetchOptions.priority = this.options.fetchPriority;
15709
15609
  }
15710
- catch (fetchError) {
15711
- clearTimeout(timeoutId);
15712
- throw fetchError;
15610
+ const response = await fetch(proxyUrl, fetchOptions);
15611
+ clearTimeout(timeoutId);
15612
+ if (!response.ok) {
15613
+ throw new Error(`代理请求失败: ${response.status}`);
15713
15614
  }
15615
+ const blob = await response.blob();
15616
+ const dataUrl = await this.blobToDataUrl(blob);
15617
+ // 缓存结果(带时间戳,10分钟有效)
15618
+ this.setCachedImage(url, dataUrl);
15619
+ return dataUrl;
15714
15620
  }
15715
- catch (error) {
15716
- if (!this.options.silentMode) {
15717
- console.warn(`📸 代理处理图片失败: ${url.substring(0, 100)}...`, error);
15718
- }
15719
- // 失败时返回原 URL
15720
- return url;
15621
+ catch (fetchError) {
15622
+ clearTimeout(timeoutId);
15623
+ throw fetchError;
15624
+ }
15625
+ }
15626
+ catch (error) {
15627
+ if (!this.options.silentMode) {
15628
+ console.warn(`📸 代理处理图片失败: ${url.substring(0, 100)}...`, error);
15721
15629
  }
15630
+ // 失败时返回原 URL,让 modern-screenshot 自己处理
15631
+ return url;
15722
15632
  }
15723
- // 如果没有配置代理,直接返回原 URL,让 modern-screenshot 自己处理
15724
- // 不再主动下载图片,避免阻塞和耗时过长
15725
- // 如果 modern-screenshot 无法处理跨域图片,建议配置代理服务器
15726
- return url;
15727
15633
  };
15728
15634
  // 检查元素是否可见且有尺寸
15729
15635
  const rect = element.getBoundingClientRect();
@@ -15741,6 +15647,8 @@ class ScreenshotManager {
15741
15647
  else {
15742
15648
  // 自动计算 workerNumber
15743
15649
  const cpuCores = navigator.hardwareConcurrency || 4; // 默认假设 4 核
15650
+ const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
15651
+ const isLowEndDevice = navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4;
15744
15652
  if (isMobile || isLowEndDevice) {
15745
15653
  // 移动设备/低端设备:使用 1 个 Worker(避免内存压力)
15746
15654
  workerNumber = 1;
@@ -15762,279 +15670,86 @@ class ScreenshotManager {
15762
15670
  }
15763
15671
  // 限制 workerNumber 范围:1-8(避免过多 Worker 导致资源竞争)
15764
15672
  workerNumber = Math.max(1, Math.min(8, workerNumber));
15765
- // 构建 createContext 配置
15766
- // 参考: https://github.com/qq15725/modern-screenshot/blob/main/src/options.ts
15767
- const contextOptions = {
15768
- workerNumber, // Worker 数量,> 0 启用 Worker 模式
15769
- quality: finalQuality, // 图片质量(0-1),已优化为更低的值以减少 base64 大小
15770
- fetchFn: handleCrossOriginImage, // 使用代理服务器处理跨域图片
15771
- fetch: {
15772
- requestInit: {
15773
- cache: 'no-cache',
15774
- },
15775
- bypassingCache: true,
15776
- },
15777
- // 设置最大 canvas 尺寸,防止生成过大的 canvas(避免内存问题)
15778
- // 参考: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size
15779
- // 大多数浏览器限制为 16,777,216 像素(4096x4096),这里设置为更保守的值
15780
- maximumCanvasSize: 16777216, // 16M 像素(约 4096x4096)
15781
- // 使用 modern-screenshot 内置的 timeout(更可靠)
15782
- timeout: Math.max(this.options.interval * 6, 5000),
15783
- };
15784
- // 限制 timeout 最多 15 秒
15785
- contextOptions.timeout = Math.min(contextOptions.timeout, 15000);
15786
- // 如果用户指定了 workerUrl,使用指定的 URL
15787
- // 否则让 modern-screenshot 自动处理(它会尝试从 node_modules 或 CDN 加载)
15788
- // 注意:在某些构建工具(如 Rollup)中,可能需要手动指定 workerUrl
15789
- if (this.options.workerUrl) {
15790
- contextOptions.workerUrl = this.options.workerUrl;
15673
+ // 按照 demo 的方式:只在 context 不存在时创建,之后一直复用
15674
+ // 不进行复杂的检测和重新创建逻辑
15675
+ if (!this.screenshotContext) {
15791
15676
  if (!this.options.silentMode) {
15792
- console.log(`📸 使用指定的 Worker URL: ${this.options.workerUrl}`);
15677
+ console.log(`📸 创建截图 Worker 上下文...`);
15678
+ console.log(`📸 Worker 模式: ${workerNumber} 个 Worker`);
15793
15679
  }
15794
- }
15795
- else {
15796
- // 未指定 workerUrl 时,modern-screenshot 会自动处理
15797
- // 但在某些构建环境中可能需要手动指定,可以使用 CDN 作为后备
15798
- // 这里不设置 workerUrl,让 modern-screenshot 自己处理
15799
- if (!this.options.silentMode) {
15800
- console.log('📸 Worker URL 未指定,modern-screenshot 将自动处理');
15801
- }
15802
- }
15803
- // 对所有元素都设置尺寸限制(包括 document.body),避免截图过大
15804
- // 这样可以减少 base64 大小,提高性能
15805
- if (finalWidth && finalHeight) {
15806
- contextOptions.width = finalWidth;
15807
- contextOptions.height = finalHeight;
15808
- if (!this.options.silentMode) {
15809
- if (element === document.body || element === document.documentElement) {
15810
- console.log(`📸 截取完整页面(document.body),使用压缩尺寸: ${finalWidth}x${finalHeight}`);
15811
- }
15812
- else {
15813
- console.log(`📸 使用压缩尺寸: ${finalWidth}x${finalHeight}`);
15814
- }
15815
- }
15816
- }
15817
- else {
15818
- if (!this.options.silentMode) {
15819
- console.log(`📸 使用元素实际尺寸: ${elementWidth}x${elementHeight}`);
15820
- }
15821
- }
15822
- // 缩放配置:使用外部传递的参数
15823
- // scale < 1 会降低图片分辨率,减少 base64 大小
15824
- if (this.options.scale !== undefined && this.options.scale !== 1) {
15825
- contextOptions.scale = this.options.scale;
15826
- }
15827
- // 优化:复用 context,避免频繁创建和销毁(性能提升 20%+)
15828
- // 只在元素变化、配置变化或内容变化时重新创建 context
15829
- // 1. 计算配置哈希
15830
- const contextOptionsHash = JSON.stringify({
15831
- workerNumber,
15832
- quality: finalQuality,
15833
- scale: contextOptions.scale,
15834
- width: contextOptions.width,
15835
- height: contextOptions.height,
15836
- maximumCanvasSize: contextOptions.maximumCanvasSize,
15837
- timeout: contextOptions.timeout
15838
- });
15839
- // 2. 计算 DOM 内容哈希(检测内容变化)
15840
- // 通过检测图片 URL、文本内容等来判断内容是否变化
15841
- // 注意:modern-screenshot 的 context 在创建时会"快照" DOM 状态
15842
- // 如果 DOM 内容变化了,必须重新创建 context 才能捕获最新内容
15843
- const contentHash = this.calculateContentHash(element);
15844
- // 3. 检查 context 是否过期(超过最大存活时间)
15845
- // 缩短过期时间,确保频繁变化的内容能及时更新
15846
- const now = Date.now();
15847
- const isContextExpired = this.contextLastUpdateTime > 0 &&
15848
- (now - this.contextLastUpdateTime) > this.contextMaxAge;
15849
- // 4. 判断是否需要重新创建 context
15850
- // 关键:如果内容哈希变化,必须重新创建 context(modern-screenshot 的限制)
15851
- const needsRecreateContext = !this.screenshotContext ||
15852
- this.contextElement !== element ||
15853
- this.contextOptionsHash !== contextOptionsHash ||
15854
- this.contextContentHash !== contentHash || // 内容变化时强制重新创建
15855
- isContextExpired;
15856
- if (needsRecreateContext) {
15857
- if (!this.options.silentMode) {
15858
- if (this.screenshotContext) {
15859
- let reason = '检测到';
15860
- if (this.contextElement !== element)
15861
- reason += '元素变化';
15862
- if (this.contextOptionsHash !== contextOptionsHash)
15863
- reason += '配置变化';
15864
- if (this.contextContentHash !== contentHash)
15865
- reason += '内容变化';
15866
- if (isContextExpired)
15867
- reason += 'context 过期';
15868
- console.log(`📸 ${reason},重新创建 context...`);
15869
- }
15870
- else {
15871
- console.log(`📸 Worker 模式: ${workerNumber} 个 Worker,质量: ${finalQuality.toFixed(2)},缩放: ${contextOptions.scale || 1}`);
15680
+ // 简化 createContext 配置,只传必要的参数(和 demo 一致)
15681
+ const simpleContextOptions = {
15682
+ workerNumber, // Worker 数量
15683
+ // 只有在配置了代理时才传递 fetchFn
15684
+ ...(shouldUseProxy ? {
15685
+ fetchFn: handleCrossOriginImage,
15686
+ fetch: {
15687
+ requestInit: {
15688
+ cache: 'no-cache',
15689
+ },
15690
+ bypassingCache: true,
15691
+ },
15692
+ } : {}),
15693
+ };
15694
+ // 如果用户指定了 workerUrl,使用指定的 URL
15695
+ if (this.options.workerUrl) {
15696
+ simpleContextOptions.workerUrl = this.options.workerUrl;
15697
+ if (!this.options.silentMode) {
15698
+ console.log(`📸 使用指定的 Worker URL: ${this.options.workerUrl}`);
15872
15699
  }
15873
15700
  }
15874
- // 销毁旧 context
15875
- if (this.screenshotContext) {
15876
- try {
15877
- destroyContext(this.screenshotContext);
15878
- }
15879
- catch (e) {
15880
- // 忽略清理错误
15701
+ else {
15702
+ if (!this.options.silentMode) {
15703
+ console.log('📸 Worker URL 未指定,modern-screenshot 将自动处理');
15881
15704
  }
15882
- this.screenshotContext = null;
15883
- }
15884
- // 添加 progress 回调(可选,用于显示进度)
15885
- if (!this.options.silentMode) {
15886
- contextOptions.progress = (current, total) => {
15887
- if (total > 0) {
15888
- const percent = Math.round((current / total) * 100);
15889
- if (percent % 25 === 0 || current === total) { // 每 25% 或完成时打印
15890
- console.log(`📸 截图进度: ${current}/${total} (${percent}%)`);
15891
- }
15892
- }
15893
- };
15894
15705
  }
15895
- // 添加重试机制创建新 context
15896
- let retries = 0;
15897
- const maxRetries = this.options.maxRetries || 2;
15898
- while (retries <= maxRetries) {
15899
- try {
15900
- // 等待图片加载完成(确保内容是最新的)
15901
- await this.waitForImagesToLoad(element);
15902
- // 等待 DOM 更新完成(确保内容渲染完成)
15903
- // 使用双重 requestAnimationFrame + setTimeout 确保内容完全渲染
15904
- await new Promise(resolve => {
15905
- requestAnimationFrame(() => {
15906
- requestAnimationFrame(() => {
15907
- // 根据截图间隔调整等待时间:频繁截图时等待更久
15908
- const waitTime = this.options.interval < 2000 ? 200 : 100;
15909
- setTimeout(resolve, waitTime);
15910
- });
15911
- });
15912
- });
15913
- // 创建 context 前,再次检查内容是否变化(防止在等待期间内容又变化了)
15914
- const latestContentHash = this.calculateContentHash(element);
15915
- if (latestContentHash !== contentHash) {
15916
- if (!this.options.silentMode) {
15917
- console.log('📸 等待期间内容发生变化,更新内容哈希');
15918
- }
15919
- // 更新 contentHash,但继续使用新的 context
15920
- // 这样下次截图时会检测到变化
15921
- }
15922
- this.screenshotContext = await createContext$1(element, contextOptions);
15923
- this.contextElement = element;
15924
- this.contextOptionsHash = contextOptionsHash;
15925
- this.contextContentHash = contentHash;
15926
- this.contextLastUpdateTime = now;
15927
- break;
15928
- }
15929
- catch (error) {
15930
- if (retries === maxRetries) {
15931
- throw new Error(`创建截图上下文失败(已重试 ${maxRetries} 次): ${error instanceof Error ? error.message : String(error)}`);
15932
- }
15933
- retries++;
15934
- const delay = 1000 * retries; // 递增延迟:1秒、2秒...
15935
- if (!this.options.silentMode) {
15936
- console.warn(`📸 ⚠️ 创建截图上下文失败,${delay}ms 后重试 (${retries}/${maxRetries})...`);
15937
- }
15938
- await new Promise(resolve => setTimeout(resolve, delay));
15706
+ try {
15707
+ this.screenshotContext = await createContext$1(element, simpleContextOptions);
15708
+ if (!this.options.silentMode) {
15709
+ console.log('📸 Worker 上下文创建成功');
15939
15710
  }
15940
15711
  }
15941
- }
15942
- else {
15943
- if (!this.options.silentMode) {
15944
- console.log('📸 复用现有 context(性能优化)');
15945
- }
15946
- // ⚠️ 重要:modern-screenshot 的 context 在创建时会"快照" DOM 状态
15947
- // 如果 DOM 内容在 context 创建后发生了变化,复用 context 会捕获到旧内容
15948
- // 因此,我们需要在每次截图前再次检查内容是否变化
15949
- // 再次计算内容哈希,检查是否在复用期间内容又变化了
15950
- const latestContentHash = this.calculateContentHash(element);
15951
- if (latestContentHash !== this.contextContentHash) {
15952
- // 内容在复用期间又变化了,必须重新创建 context
15712
+ catch (error) {
15953
15713
  if (!this.options.silentMode) {
15954
- console.log('📸 ⚠️ 复用期间检测到内容变化,强制重新创建 context');
15955
- }
15956
- // 销毁旧 context
15957
- if (this.screenshotContext) {
15958
- try {
15959
- destroyContext(this.screenshotContext);
15960
- }
15961
- catch (e) {
15962
- // 忽略清理错误
15963
- }
15964
- this.screenshotContext = null;
15965
- }
15966
- // 等待图片加载和 DOM 更新
15967
- await this.waitForImagesToLoad(element);
15968
- await new Promise(resolve => {
15969
- requestAnimationFrame(() => {
15970
- requestAnimationFrame(() => {
15971
- const waitTime = this.options.interval < 2000 ? 200 : 100;
15972
- setTimeout(resolve, waitTime);
15973
- });
15974
- });
15975
- });
15976
- // 重新创建 context
15977
- let retries = 0;
15978
- const maxRetries = this.options.maxRetries || 2;
15979
- while (retries <= maxRetries) {
15980
- try {
15981
- this.screenshotContext = await createContext$1(element, contextOptions);
15982
- this.contextElement = element;
15983
- this.contextOptionsHash = contextOptionsHash;
15984
- this.contextContentHash = latestContentHash;
15985
- this.contextLastUpdateTime = Date.now();
15986
- break;
15987
- }
15988
- catch (error) {
15989
- if (retries === maxRetries) {
15990
- throw new Error(`重新创建截图上下文失败(已重试 ${maxRetries} 次): ${error instanceof Error ? error.message : String(error)}`);
15991
- }
15992
- retries++;
15993
- const delay = 1000 * retries;
15994
- if (!this.options.silentMode) {
15995
- console.warn(`📸 ⚠️ 重新创建截图上下文失败,${delay}ms 后重试 (${retries}/${maxRetries})...`);
15996
- }
15997
- await new Promise(resolve => setTimeout(resolve, delay));
15998
- }
15714
+ console.error('📸 创建 Worker 上下文失败:', error);
15999
15715
  }
16000
- }
16001
- else {
16002
- // 内容没有变化,可以安全复用 context
16003
- // 但还是要等待图片加载完成,确保内容是最新的
16004
- await this.waitForImagesToLoad(element);
16005
- // 等待 DOM 更新完成
16006
- await new Promise(resolve => {
16007
- requestAnimationFrame(() => {
16008
- requestAnimationFrame(() => {
16009
- setTimeout(resolve, 100); // 额外等待 100ms,确保内容完全渲染
16010
- });
16011
- });
16012
- });
15716
+ throw error;
16013
15717
  }
16014
15718
  }
16015
15719
  try {
16016
- // 根据输出格式选择对应的 API,避免格式转换(性能优化)
16017
- // 注意:timeout 已经在 createContext 时设置,modern-screenshot 内部会处理超时
15720
+ // 按照 demo 的方式:使用 domToWebp 时传递配置参数
16018
15721
  let dataUrl;
16019
15722
  const outputFormat = this.options.outputFormat || 'webp';
16020
15723
  if (!this.options.silentMode) {
16021
15724
  console.log(`📸 使用 ${outputFormat.toUpperCase()} 格式截图(直接输出,无需转换)...`);
16022
15725
  }
15726
+ // 构建 domToWebp/domToJpeg/domToPng 的配置参数(和 demo 一致)
15727
+ const screenshotOptions = {
15728
+ scale: this.options.scale ?? 0.7, // 使用外部参数,默认 0.7(和 demo 一致)
15729
+ backgroundColor: this.options.backgroundColor ?? '#ffffff', // 默认白色背景
15730
+ type: `image/${outputFormat}`, // 使用配置的输出格式
15731
+ quality: this.options.quality ?? 0.6, // 使用外部参数,默认 0.6(和 demo 一致)
15732
+ drawImageInterval: this.options.drawImageInterval ?? 20, // 默认 20ms(和 demo 一致)
15733
+ features: {
15734
+ copyScrollbar: false,
15735
+ removeAbnormalAttributes: true,
15736
+ removeControlCharacter: true,
15737
+ fixSvgXmlDecode: true,
15738
+ restoreScrollPosition: false,
15739
+ },
15740
+ timeout: 10000, // 10秒超时(和 demo 一致)
15741
+ };
16023
15742
  // 尝试使用 Worker 模式(context)
16024
15743
  try {
16025
- // 根据输出格式选择对应的 API
16026
- // modern-screenshot 内部已经处理了超时,不需要额外的 Promise.race
15744
+ // 根据输出格式选择对应的 API,传递配置参数(和 demo 一致)
16027
15745
  if (outputFormat === 'webp') {
16028
- // 使用 domToWebp,直接输出 WebP 格式,无需转换
16029
- dataUrl = await domToWebp(this.screenshotContext);
15746
+ dataUrl = await domToWebp(this.screenshotContext, screenshotOptions);
16030
15747
  }
16031
15748
  else if (outputFormat === 'jpeg') {
16032
- // 使用 domToJpeg,直接输出 JPEG 格式,无需转换
16033
- dataUrl = await domToJpeg(this.screenshotContext);
15749
+ dataUrl = await domToJpeg(this.screenshotContext, screenshotOptions);
16034
15750
  }
16035
15751
  else {
16036
- // 默认使用 domToPng
16037
- dataUrl = await domToPng(this.screenshotContext);
15752
+ dataUrl = await domToPng(this.screenshotContext, screenshotOptions);
16038
15753
  }
16039
15754
  // 验证截图结果
16040
15755
  if (!dataUrl || dataUrl.length < 100) {
@@ -16046,7 +15761,7 @@ class ScreenshotManager {
16046
15761
  return dataUrl;
16047
15762
  }
16048
15763
  catch (workerError) {
16049
- // Worker 模式失败,回退到普通模式(参考用户代码)
15764
+ // Worker 模式失败,回退到普通模式(和 demo 一致)
16050
15765
  if (!this.options.silentMode) {
16051
15766
  console.warn('📸 Worker 模式失败,回退到普通模式:', workerError);
16052
15767
  }
@@ -16060,14 +15775,14 @@ class ScreenshotManager {
16060
15775
  }
16061
15776
  this.screenshotContext = null;
16062
15777
  }
16063
- // 回退到普通模式(直接使用 domToWebp,不传 context)
16064
- // 使用外部传递的参数,并给出合理的默认值
15778
+ // 回退到普通模式(直接使用 element,不传 context)
15779
+ // 使用更低的参数(和 demo 一致)
16065
15780
  const fallbackOptions = {
16066
- scale: this.options.scale ?? 1, // 使用外部参数,默认 1
16067
- backgroundColor: '#ffffff', // 默认白色背景
16068
- type: `image/${outputFormat}`, // 使用配置的输出格式
16069
- quality: this.options.quality ?? 0.8, // 使用外部参数,默认 0.4
16070
- drawImageInterval: 20, // 默认 20ms,减少主线程阻塞
15781
+ scale: 0.3, // 回退模式使用更低的 scale(和 demo 一致)
15782
+ backgroundColor: this.options.backgroundColor ?? '#ffffff',
15783
+ type: `image/${outputFormat}`,
15784
+ quality: 0.3, // 回退模式使用更低的质量(和 demo 一致)
15785
+ drawImageInterval: this.options.drawImageInterval ?? 20,
16071
15786
  features: {
16072
15787
  copyScrollbar: false,
16073
15788
  removeAbnormalAttributes: true,
@@ -16075,10 +15790,8 @@ class ScreenshotManager {
16075
15790
  fixSvgXmlDecode: true,
16076
15791
  restoreScrollPosition: false,
16077
15792
  },
16078
- timeout: Math.max((this.options.interval ?? 5000) * 6, 10000), // 使用外部参数计算超时,默认 10
15793
+ timeout: 10000, // 10秒超时(和 demo 一致)
16079
15794
  };
16080
- // 限制 timeout 最多 15 秒
16081
- fallbackOptions.timeout = Math.min(fallbackOptions.timeout, 15000);
16082
15795
  if (outputFormat === 'webp') {
16083
15796
  dataUrl = await domToWebp(element, fallbackOptions);
16084
15797
  }
@@ -17425,10 +17138,6 @@ class ScreenshotManager {
17425
17138
  // 忽略清理错误
17426
17139
  }
17427
17140
  this.screenshotContext = null;
17428
- this.contextElement = null;
17429
- this.contextOptionsHash = '';
17430
- this.contextContentHash = '';
17431
- this.contextLastUpdateTime = 0;
17432
17141
  }
17433
17142
  if (!this.options.silentMode) {
17434
17143
  console.log(`📸 截图引擎已更新: ${oldEngine} → ${newEngine}`);
@@ -17452,10 +17161,6 @@ class ScreenshotManager {
17452
17161
  // 忽略清理错误
17453
17162
  }
17454
17163
  this.screenshotContext = null;
17455
- this.contextElement = null;
17456
- this.contextOptionsHash = '';
17457
- this.contextContentHash = '';
17458
- this.contextLastUpdateTime = 0;
17459
17164
  }
17460
17165
  this.stopScreenshot();
17461
17166
  if (this.worker) {