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

Playwright文件上传测试在GitLab CI的Firefox中报错:frame.setInputFiles: Target closed

Playwright Firefox文件上传在GitLab CI中报“frame.setInputFiles: Target closed”问题解决

问题背景

  • 本地Windows环境(Playwright 1.35.1升级至1.43.1):Chromium、Firefox(无头/有头模式)均能正常完成文件上传测试
  • GitLab CI环境(基于debian:11.7-slim镜像,同版本Playwright+最新浏览器依赖):Chromium测试通过,Firefox执行setInputFiles时抛出frame.setInputFiles: Target closed错误
  • 已尝试无效操作:改用fileChooser方式上传、升级Playwright到最新版
  • 本地特殊现象:Firefox上传后文件浏览窗口需10秒才消失(此时浏览器窗口已关闭)

可能原因

  1. Firefox无头模式下的文件选择弹窗处理逻辑与本地有头/Chromium存在差异,CI环境中页面上下文可能因弹窗未及时处理被销毁
  2. Debian slim镜像为精简版,缺少Firefox无头模式处理文件上传所需的底层依赖
  3. CI环境的网络/渲染速度慢于本地,点击“Upload Files”后文件输入框未完全就绪就执行上传操作,导致上下文异常

解决方案

1. 确保元素就绪后再执行上传

在操作文件输入框前,等待元素完全可交互,避免过早操作触发上下文异常:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  await page.goto('https://www.file.io/');
  await page.getByText('Upload Files').click();
  const fileInputElement = page.locator('#upload-button');
  
  // 等待元素可交互,确认页面上下文稳定
  await expect(fileInputElement).toBeEnabled();
  await fileInputElement.setInputFiles('dummy.pdf');
  
  // 额外等待上传操作触发后的页面状态稳定
  await page.waitForTimeout(1000);
});

2. 禁用Firefox原生文件选择弹窗

通过浏览器启动参数强制禁用系统级文件选择弹窗,消除弹窗导致的上下文干扰:
修改playwright.config.ts中Firefox项目的配置:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'firefox',
      use: {
        ...devices['Desktop Firefox'],
        launchOptions: {
          args: ['--disable-native-file-dialogs', '--disable-file-system-access-api']
        }
      },
    },
  ],
});

3. 补充CI镜像的底层依赖

Debian slim镜像可能缺失Firefox运行所需的库,在CI脚本中添加依赖安装步骤:

# 在CI任务的Playwright安装前执行
apt-get update && apt-get install -y --no-install-recommends libgtk-3-0 libdbus-glib-1-2 libxt6 libx11-xcb1

4. 调整FileChooser等待时机

提前监听filechooser事件,确保弹窗触发后再执行文件设置:

import { test } from '@playwright/test';

test('test', async ({ page }) => {
  await page.goto('https://www.file.io/');
  
  // 先监听filechooser事件,再点击上传按钮
  const fileChooserPromise = page.waitForEvent('filechooser');
  await page.getByText('Upload Files').click();
  
  const fileChooser = await fileChooserPromise;
  await fileChooser.setFiles('dummy.pdf');
});

验证步骤

  1. 优先尝试方案1,调整等待逻辑,观察CI中Firefox测试是否正常
  2. 若无效,添加方案2的浏览器启动参数,禁用原生弹窗
  3. 最后检查并补充CI镜像的底层依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:33:27