The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounters an error: locator.innerText: Target closed
, which specifically relates to the definition of rows
.
The issue can be temporarily resolved by commenting out the line await context.close();
. However, this leads to the undesired outcome of the terminal session hanging.
Why does the error occur and how can it be addressed?
import { firefox } from 'playwright';
(async () => {
const browser = await firefox.launch({ headless: true });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(
'https://example.com'
);
const rows = await page
.locator('.row')
.filter({ hasText: 'some text that some rows have' })
.all();
rows.forEach(async (row) => {
const time = await row.locator('.time').innerText();
const heading = await row.getByText('some common heading').innerText();
console.log(`${time} ${heading}`);
});
// Uncommenting the following line causes the script to fail with the error
// `locator.innerText: Target closed`.
// If the following line is left commented, the script logs the expected output but
// leaves the browser open resulting in a hung terminal session.
await context.close();
})();