You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中捕获含系统任务栏日期时间戳的全屏截图?

解决Cypress无法捕获系统任务栏日期时间的全屏截图问题

Cypress默认的cy.screenshot()只能捕获浏览器视口内的内容,无法获取系统任务栏这类操作系统级别的UI元素。要实现包含系统任务栏的全屏截图,需要借助系统级工具或Node.js第三方库,以下是两种可行方案:

方案一:调用系统自带截图命令

通过Cypress的cy.exec()执行操作系统的原生截图命令,直接捕获整个屏幕:

  • Windows系统:
    使用PowerShell调用PrintScreen或截图工具:
    cy.exec('powershell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait(\'{PRTSC}\')"')
    # 也可直接调用SnippingTool实现延迟截图
    cy.exec('snippingtool /clip /delay 1000')
    
  • macOS系统:
    使用screencapture命令直接保存全屏截图:
    cy.exec('screencapture -x full-screen.png')
    
  • Linux系统:
    使用scrot工具(需提前安装):
    cy.exec('scrot full-screen.png')
    

方案二:通过Node.js第三方库实现

利用Node.js的桌面截图库,在Cypress任务中调用系统级截图API:

  1. 安装依赖库(以desktop-screenshot为例):
    npm install desktop-screenshot --save-dev
    
  2. 在cypress.config.js中配置自定义任务:
    const screenshot = require('desktop-screenshot');
    const { defineConfig } = require('cypress');
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          on('task', {
            takeFullScreenScreenshot(filename) {
              return new Promise((resolve, reject) => {
                screenshot(filename, (err, res) => {
                  if (err) reject(err);
                  else resolve(res);
                });
              });
            }
          });
        },
      },
    });
    
  3. 在测试用例中调用该任务:
    cy.task('takeFullScreenScreenshot', 'full-screen-with-taskbar.png');
    

注意事项

  • 系统命令方案需根据操作系统做兼容处理,确保测试环境安装了对应工具;
  • 使用第三方库时,部分系统(如macOS)需要授予应用(终端/VS Code等)屏幕录制权限;
  • 两种方案都能捕获包含系统任务栏的全屏内容,可根据测试环境和需求选择。

内容的提问来源于stack exchange,提问作者Mathi Vanan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:35:45