ArticleZip > How Can I Check That An Element Is Visible With Puppeteer And Pure Javascript

How Can I Check That An Element Is Visible With Puppeteer And Pure Javascript

When working with Puppeteer and pure JavaScript, it's important to ensure that elements on a webpage are not only present but also visible to users. In this article, we'll dive into how you can check if an element is visible using Puppeteer and JavaScript.

Puppeteer is a powerful tool for automating web browser actions, which is especially handy for testing and scraping websites. However, detecting element visibility can sometimes be tricky in automated scripts. But worry not, we've got you covered with a simple approach to tackle this challenge.

To determine if an element is visible on a webpage, we need to tap into the underlying logic of how web browsers render elements. When an element is visible, it means that it occupies space on the screen and is not hidden or obscured by other elements or styling properties like 'display: none' or 'visibility: hidden'.

Let's jump into the code! First, ensure you have Puppeteer installed in your project:

Bash

npm install puppeteer

Next, let's set up a basic script that creates a Puppeteer instance, navigates to a webpage, and checks if a specific element is visible:

Javascript

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://example.com');

  const element = await page.$('#your-element-selector');
  const isElementVisible = await page.evaluate(element => {
    const style = window.getComputedStyle(element);
    return style && style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
  }, element);

  console.log('Is element visible:', isElementVisible);

  await browser.close();
})();

In the code snippet above, we launch a Puppeteer browser, navigate to a webpage, select a specific element with the `page.$` method using a CSS selector, and then use `page.evaluate` to run a script in the browser context to determine if the element is visible based on its computed styles.

The script checks if the `display` property is not set to 'none', the `visibility` property is not 'hidden', and the opacity is not set to '0'. If all conditions are `true`, the element is considered visible.

Remember to replace `'https://example.com'` with the URL of the webpage you're testing and `'#your-element-selector'` with the CSS selector of the element you want to check for visibility.

By incorporating this code into your Puppeteer scripts, you can now efficiently check if an element is visible on a webpage. This technique is valuable for automated testing scenarios where verifying element visibility is crucial for ensuring the functionality and user experience of web applications.

×