Skip to content

Instantly share code, notes, and snippets.

@pauloeli
Created February 21, 2023 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauloeli/7cbc6504c19f27ac6c469df13d41fec2 to your computer and use it in GitHub Desktop.
Save pauloeli/7cbc6504c19f27ac6c469df13d41fec2 to your computer and use it in GitHub Desktop.
Simulate browser NodeJS (simple)
// 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