Skip to content

Instantly share code, notes, and snippets.

@a5ync
Created November 16, 2023 05:59
Show Gist options
  • Save a5ync/f90a5ddca7c32be438fb5c502bbb5c78 to your computer and use it in GitHub Desktop.
Save a5ync/f90a5ddca7c32be438fb5c502bbb5c78 to your computer and use it in GitHub Desktop.
Playwright awaiter, it uses querySelector to check if DOM object has been populated with the content
import { chromium } from "playwright";
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('http://localhost:3000');
const selector = 'div#my-div';
const timeout = 5;
const desiredData = page.locator(selector);
try {
await desiredData.waitFor({ state: 'attached', timeout: timeout * 1000 });
const textContent = await desiredData.textContent();
console.log(`Text content of the div after attached: ${textContent}`);
/**
* the following section will wait until element actually has text content or timeout
*/
await page.waitForFunction((sel) => {
const el = document.querySelector(sel);
return el && el.textContent && el.textContent.trim().length > 0;
}, selector, { timeout: timeout * 1000 })
const textContentAfter = await desiredData.textContent();
console.log(`Text content of the div after attached: ${textContentAfter}`);
} catch (error) {
console.error(error);
}
await browser.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment