Created
February 21, 2023 13:16
-
-
Save pauloeli/7cbc6504c19f27ac6c469df13d41fec2 to your computer and use it in GitHub Desktop.
Simulate browser NodeJS (simple)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dependencia: | |
// "playwright-chromium": "^1.12.3", | |
import {BrowserContext, Page} from 'playwright-chromium/types/types'; | |
const playwright = require('playwright-chromium'); | |
const logger = require('../helpers/logger'); | |
export class Browser { | |
constructor() { | |
} | |
async init(): Promise<BrowserContext> { | |
try { | |
const browser = await playwright['chromium'].launch(); | |
const context = await browser.newContext(); | |
return Promise.resolve(context); | |
} catch (reason) { | |
logger.error(`erro ao inicializar a instância do navegador, motivo: ${reason?.message || reason}`); | |
throw reason; | |
} | |
} | |
async doLogin(context: BrowserContext): Promise<void> { | |
try { | |
const page = await context.newPage(); | |
await page.goto(`url`); | |
await this.setTextInputValue(page, 'input[name="email"]', String(process.env.USR)); | |
await this.setTextInputValue(page, 'input[name="password"]', String(process.env.PSWD)); | |
await this.clickAndWaitNavegation(page, 'button[type=submit]'); | |
} catch (reason) { | |
logger.error(`erro ao efetuar login, motivo: ${reason?.message || reason}`); | |
throw reason; | |
} | |
} | |
public async setTextInputValue(page: Page, selector: string, value: string | number) { | |
await page.waitForSelector(selector); | |
await page.evaluate((data) => { | |
let querySelector: any = document.querySelector(data.selector); | |
return querySelector ? querySelector.value = data.value : null; | |
}, {selector, value}); | |
} | |
public async clickAndWaitNavegation(page: Page, selector: string) { | |
const navigationPromise = page.waitForNavigation(); | |
await page.click(selector); | |
await navigationPromise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment