The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

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();
})();

Answer №1

The issue arises due to the fact that the forEach loop does not wait for asynchronous operations inside it to complete, leading to a faster execution of context.close().

Using async/await with forEach is not possible. It is recommended to switch to for...of instead:

for (const row of rows) {
  const time = await row.locator('.time').innerText();
  const heading = await row.getByText('some common heading').innerText();

  console.log(`${time} ${heading}`);
}

Furthermore, when closing the terminal session, make sure to use browser.close() instead of context.close().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

When triggering the fireEvent.mouseOver event, it seems that document.createRange is not a valid

Having trouble using fireClick.mouseOver(tab) to test tooltip functionality on tab hover. Here's a snippet of the code: it('should handle change on hover of tab', () => { const {getByTestId, getByRole} = renderComponent('Dra ...

Divide the information in the table across several pages for easier printing

I have encountered an architectural challenge with my server-side React app. The app renders charts and tables with page breaks in between to allow a puppeteer instance to print the report for users in another application. The issue I'm facing is mak ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

An element failing to submit using AJAX requests

I have a login form with an <a> element that I want to use for making a post request. However, when I'm examining the backend Django code during debugging, it seems to interpret the request method as GET instead of POST. HTML <form id= ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Tips for expanding a fabric canvas to match the entire width of its parent division

specific scenario I have a cloth canvas placed inside a main section. How can I expand the canvas to cover the entire width and height of its container? Here is what my current code looks like: <div class="design_editor_div"> &l ...

Setting a cookie using express.js with a 'j' prefix

Trying to establish a cookie using res.cookie as shown below: res.cookie('userId',req.user._id); //cookie set here console.log(req.user._id); //correct value returned, eg abc However, I'm noticing j:"abc" in my cookie. What could be the re ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

Navigate through fabricated data not appearing in Express application

I have come across a handlebars template file within my Express app: {{#each data}} <article class="id-{{this.id}}"> <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1> <p>{{this.body}}</p> </ar ...

Utilizing Vue's string-based class binding feature?

Can Vue class binding work with strings? For example: <div :class={open: target == 'myString'}></div> var app = new Vue({ target: null }) It works when I don't use quotes <div :class={open: target == myString}></div ...

Please do not exceed two words in the input field

I need to restrict the input field to only allow up to two words to be entered. It's not about the number of characters, but rather the number of words. Can this restriction be achieved using jQuery Validation? If not, is there a way to implement it u ...

The Chrome extension for the New Tab Page is taking the spotlight away from the address bar

It appears that with the latest version of Chrome, extensions that previously had the ability to override Chrome's New Tab Page and take focus away from the Omnibox no longer have this capability. Is there a different method now to give focus to an i ...

A guide to iterating over an array and displaying individual elements in Vue

In my application, there is a small form where users can add a date with multiple start and end times which are then stored in an array. This process can be repeated as many times as needed. Here is how the array structure looks: datesFinal: {meetingName: ...

The Server-Side Rendered page is experiencing inconsistencies in rendering

I am currently working on a straightforward NextJS project with just one page. The application is configured to utilize redux, next-redux-wrapper, and redux thunk. It is important that the page always undergo server-side rendering. Here is an example of h ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

How to handle blank property values in JavaScript objects and convert them to null in an ASP.NET Web API

Hey there! I'm facing an issue where when I post a JavaScript object to an ASP.NET Web API, some property values are blank like the example below: var o={ ID=1, Fname="Tom", Mname="", Lname="Wilson" } However, in the Web ...