/**
* Retrieves an OTP from Gmail in a headless tab.
* @param {Object} options - The options for the function.
* @param {string} options.email - The Gmail email address.
* @param {string} options.password - The Gmail password.
* @returns {Promise<string | null>} The OTP retrieved from the email.
*/
export async function getOtpFromGmail({
email,
password,
}: {
email: string;
password: string;
}): Promise<string | null> {
const { chromium } = require("playwright");
// Launch a headless browser context for Gmail login
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("https://mail.google.com");
const emailInput = await page.waitForSelector("#identifierId");
await emailInput.fill(email);
const emailNextButton = await page.waitForSelector("#identifierNext button", { timeout: 2000 });
await emailNextButton.click();
const passwordInput = await page.waitForSelector("input[type='password']", { timeout: 4000 });
await passwordInput.fill(password);
const passwordNextButton = await page.waitForSelector("#passwordNext button", { timeout: 2000 });
await passwordNextButton.click();
await page.waitForURL("https://mail.google.com/mail/u/0/#inbox", { timeout: 25000 });
// Open the latest email from the OTP provider
const emails = await page.$$(`span[email='<provider email>']`);
if (emails.length > 1) {
await emails[1].click();
}
// Look for the OTP in the email content
const emailContent = await page.locator("span").allInnerTexts();
const otpRegex = /\b(\d{6})\b/;
for (const text of emailContent) {
const match = text.match(otpRegex);
if (match) {
await browser.close(); // Close the headless browser
return match[1];
}
}
await browser.close();
return null;
}
Comments
Post a Comment