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

如何向Playwright的Page.evaluate()传递多个参数?

Playwright-TS 中 page.evaluate 参数传递问题解决

你的问题核心是page.evaluate的回调函数运行在浏览器上下文,无法直接访问Node.js侧的变量,必须显式传递需要的参数;另外传递参数时的类型或解构方式出错,导致apiData被识别成string。以下是两种可行的修正方案:

方案1:传递包含所有数据的对象参数(推荐)

把apiData和emailId打包成一个对象传给evaluate,回调直接解构使用,类型清晰不易出错:

async tester(page: Page, emailId: string) {
  await page.evaluate(({ apiData, emailId }) => {
    const userId = window.localStorage.getItem('userId');
    // 原代码中authentication.allCookies不存在,这里替换为浏览器端实际获取cookie的方式
    const data = { email: emailId };

    fetch(`${apiData.domain}/api/v1/user`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        cookie: document.cookie // 按需调整为实际需要的cookie值
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then(myJson => {
      // 修复变量声明和字符串转义问题
      const newUserId = JSON.stringify(myJson.data.id).replace(/"/g, "");
      // 若需将newUserId传回Node.js侧,可在此return,外部用await接收
      // return newUserId;
    });
  }, { apiData: this.apiData, emailId }); // 将需要的参数作为第二个参数传入
}

方案2:正确使用数组参数并处理类型

如果偏好数组传递,需确保解构正确,并给参数添加类型注解消除TS报错:

async tester(page: Page, emailId: string) {
  // 明确数组元素的类型,避免apiData被识别为string
  await page.evaluate(([apiData, emailId]: [{ domain: string; name: string }, string]) => {
    const userId = window.localStorage.getItem('userId');
    const data = { email: emailId };

    fetch(`${apiData.domain}/api/v1/user`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        cookie: document.cookie
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then(myJson => {
      const newUserId = JSON.stringify(myJson.data.id).replace(/"/g, "");
      // return newUserId; // 如需返回数据给Node.js侧
    });
  }, [this.apiData, emailId]); // 数组形式传递参数
}

关键注意点

  1. 上下文隔离:page.evaluate的回调运行在浏览器环境,不能直接访问Node.js侧的变量(如this.apiData、emailId),必须通过第二个参数序列化传递。
  2. 原代码的其他修复:
    • 原authentication对象中没有allCookies属性,需改用document.cookie或正确的cookie获取逻辑。
    • newUserId未声明会变成全局变量,必须添加let/const。
    • 字符串替换中的""是错误写法,需改为双引号""。
    • 若需将浏览器侧的newUserId传回Node.js,需在回调中return,外部用await接收返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:06:25