Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console:

document.querySelector('shop-app').shadowRoot.querySelector('shop-home').shadowRoot.querySelector('shop-button');
   

When attempting to access the same element in my automation test using Selenium:

Line 1:

WebElement shopBtn = (WebElement)((JavascriptExecutor)driver).executeScript("return document.querySelector('shop-app').shadowRoot.querySelector('shop-home').shadowRoot.querySelector('shop-button')");

Line 2: shopBtn.click();

This code results in the following error:

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'querySelector' of null
   (Session info: chrome=51.0.2704.106)
   (Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Mac OS X 10.11.3 x86_64).
   

Any assistance on this matter would be greatly appreciated.

Answer №1

It seems like you may be working with Java, based on your question. Below is a sample code snippet that does not rely on JSE.

WebDriver driver = new FirefoxDriver();
String searchText = "Men's Outerwear";
driver.get("https://shop.polymer-project.org/");
WebDriverWait wait = new WebDriverWait(driver, 5);
List<WebElement> sections = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("div.item")));
for (WebElement section : sections)
{
    if (section.getText().toLowerCase().contains(searchText.toLowerCase()))
    {
        section.findElement(By.linkText("SHOP NOW")).click();
        break;
    }
}

Answer №2

In order to locate the specific element, you need to iterate through each of the shadow root elements individually.

document.querySelector('nuxeo-app').shadowRoot.querySelector('nuxeo-document-create-button').shadowRoot.querySelector('paper-fab').shadowRoot.querySelector('iron-icon');

Answer №3

Attempting to execute a click operation, I successfully achieved it with the help of Firefox and an XPath locator.

.//shop-button/a[starts-with(@aria-label, 'Men') and contains(@aria-label, 'Outerwear Shop Now')]

Utilizing Selenium 3 for this task.

Uncertain if my current method is correct.

Cheers!

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

Vue Material - Effortlessly integrate native transitions within router views

In the project I'm currently working on, I have chosen to use Vue Material for the development of a single-page application. The approach I am taking follows a common trend in which a central "container" component is utilized to manage the shifting vi ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: The challenge I am facing involves updating the language of the chips based on the selection made in a dropdown menu. A ...

Incorporating items into a dynamic array using MobX

Issue with Pushing MobX Objects to an Observable Array I'm facing a challenge when trying to push objects into an observable array in MobX and iterate over them successfully. At the starting point, I initialize the observable array: if (!self.selec ...

Navigating through web pages and creating dynamic interfaces is made simple

As someone relatively new to React, I am currently exploring how to integrate React Router with Material UI. In my Layout file, I have implemented a Navigation drawer from Material UI with the menu on the left and content on the right, as depicted in the ...

Achieving proper functionality of additional directives within uib-tab components

How can I utilize a callback function for uib-tab directives to refresh inner directives after tab rendering? I'm troubleshooting an issue with a third-party directive when used within the uib-tab directive from angular-bootstrap. The specific direct ...

Angularjs is struggling to connect data to the user interface

It seems that the array is not binding properly in the UI. In the HTML code, I am using dataTables. The variable $scope.successMessage is also not binding to the UI. I have tried multiple approaches but none seem to be working. Here is a snippet of th ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

Troubleshooting issue with jQuery subtraction not functioning as expected

Everything seems to be functioning correctly except for the subtraction operation. function add_culture(ele) { total=parseInt($('#total_price').val()); culture_price=parseInt($('#culture_price').val()); $(& ...

A problem has occurred in Next.js where FileReader is not recognized and is causing a Reference

Exploring the latest features of Next.js 13 with the /app directory, I encountered an issue while using the FileReader in a basic client-side component that manages an input form. Here is a brief overview of the code: "use client"; import React, ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

Change HTML canvas data into Angular form data before sending it to the Laravel backend

My JavaScript code to convert a data URL to blob and send it as a form request is: var canv = document.getElementById("mainCanvas"); var dataURL = canv.toDataURL('image/jpg'); documentData = {"image": dataURLtoBlob(dataURL), "gameName": "empero ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code: API https://github.com/HackerNews/API BASE_URL = 'https://hacker-news.firebaseio.com ...

Displaying data using JSON on a fabric.js canvas

I've been encountering some issues while attempting to store data in JSON and then reload it onto the canvas using fabric.js. My code is quite simple: canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 })); ...

JS Issue with Generating Content

Introduction( kind of :) ) Starting with the process of generating 5 coffee beans for each cup of coffee. The coffee class includes a strength attribute, and my goal is to visually distinguish the coffee beans which have a strength greater than the select ...

What techniques can I utilize to ensure Azure function generates JSON specifically for web browsers?

I have a functioning Azure function with the following code: module.exports = function(context, req) { // this is the complete source code, believe it or not context.done(null, {favoriteNumber: 3}); }; When I utilize a tool like Postman to access ...

Utilizing the same browser session across various scenarios

In the following code, I am attempting to utilize the same browser session in different test cases. However, upon execution, it is observed that two separate browser sessions are being opened for each test case. Any suggestions on how to resolve this iss ...

Updating data in React Native fails to activate useEffect, leading to the screen not being refreshed

I'm facing a challenge while working on a recipes app using Firebase Realtime database. I have a functional prototype, but I am encountering an issue where the useEffect hook does not trigger a reload after editing the array [presentIngredients]. Her ...