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

如何暂停Puppeteer请求,获取API返回的2FA码后完成登录?

解决方案

要实现检测到2FA后暂停流程获取验证码并继续完成登录,你需要调整现有代码逻辑,移除检测到2FA后的直接返回操作,替换为调用第三方API获取验证码、填入验证框并提交的步骤。以下是具体实现:

关键修改步骤

  • 新增异步函数调用第三方API获取2FA验证码
  • 检测到2FA输入框时,暂停流程等待API返回验证码
  • 将验证码填入输入框并提交验证
  • 继续执行后续登录成功后的逻辑

修改后的完整代码

// 新增:调用第三方API获取2FA码的函数,根据你的API参数调整
const get2FACodeFromAPI = async (userId) => {
  // 这里替换为你的第三方API请求逻辑
  const response = await fetch(`https://your-2fa-api.com/get-code?user=${userId}`);
  const data = await response.json();
  return data.code; // 假设API返回的验证码字段为code
};

export const Login = async (user) => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  page.setDefaultTimeout(60000);
  await page.goto("https://www.example.com/login/");

  await page.waitForSelector("input[name=username]", { visible: true });
  await delay(100);
  await page.type("input[name=username]", user.username, { delay: 50 });

  await delay(100);
  await page.type("input[name=password]", user.password, { delay: 50 });

  await delay(100);
  await page.click('button[type="submit"]');

  try {
    let requires2FA = false;
    try {
      // 检测2FA输入框是否出现,超时时间可根据页面加载速度调整
      await page.waitForSelector('input[name="verificationCode"]', { timeout: 5000 });
      requires2FA = true;
    } catch (err) {
      console.log("No 2FA required");
    }

    if (requires2FA) {
      console.log("2FA verification required");
      // 调用API获取2FA码,暂停流程等待返回
      const twoFACode = await get2FACodeFromAPI(user.username);
      if (!twoFACode) {
        throw new Error("Failed to retrieve 2FA code from API");
      }

      // 将验证码填入2FA输入框
      await page.type('input[name="verificationCode"]', twoFACode, { delay: 30 });
      // 提交2FA验证(根据页面实际情况调整选择器,若输入后自动提交可省略此步)
      await page.click('button[type="submit"]');
    }

    // 等待登录后的页面导航完成
    await page.waitForNavigation({ waitUntil: "networkidle2" });

    console.log("Login successful");
    const cookies = await page.cookies();
    await saveCookies(user.username, cookies);

    return {
      status: 1,
      message: "Login successful",
    };
  } catch (error) {
    console.log("Login failed:", error.message);
    // 关闭浏览器避免资源泄漏
    await browser.close();
    return {
      status: 0,
      message: "Login failed:" + error.message,
    };
  } finally {
    // 可选:如果不需要保持浏览器会话,在这里统一关闭
    // await browser.close();
  }
};

关键说明

  1. API调用适配:get2FACodeFromAPI需要根据你的第三方API实际要求调整请求方式、参数和返回值解析逻辑。
  2. 2FA检测优化:通过waitForSelector的超时判断是否需要2FA,简化错误捕获逻辑,避免误判。
  3. 提交逻辑调整:2FA页面的提交按钮选择器可能和登录页不同,需根据实际页面DOM结构修改;若输入验证码后页面自动触发验证,可省略page.click步骤。
  4. 资源泄漏防护:在错误捕获块中新增浏览器关闭逻辑,避免Puppeteer进程残留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:57:36