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

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...

Which is the better choice for accessing and manipulating JSON files – using Ajax or the Node fs module?

When storing quiz questions using JSON data, should I use vanilla AJAX or Node.js file system to read the file? I am planning to develop a website where users can create quizzes and save them as JSON. I intend to utilize the Node.js fs module to save the ...

How can I initiate a TextChange event in ASP.NET C# without losing focus?

I attempted to trigger the TextChange event using Ajax, but it doesn't seem to be working as I expected. I'm hoping someone here can lend a hand. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> ...

The ng-repeat ng-switch combination is not functioning as expected

My data can be simplified to the following in my code: function DemoCtrl($scope) { $scope.myData= [ {text: "blah", other: 3, V: 'caseOne'}, {text: "blah", other: 3, V: 'caseTwo'}, {text: "blah", other: 3, V ...

Remove initial message using Selenium WebDriver in Internet Explorer

Currently working with Selenium IE Webdriver, I am trying to remove the line "This is the initial page of webdriver server." from the IEDriverServer.exe file. I edited the IEDriverServer.exe file in notepad++ by deleting that specific line and then added i ...

Is it possible to incorporate Vue and Vuetify into an existing project that requires IE compatibility?

Currently in the process of enhancing a legacy project with new functionality. The front end is currently relying solely on jQuery for all the webpages. I have been tasked with adding another webpage and would like to incorporate Vuetify + Vue due to the i ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Express.js is still displaying the 'Not Found' message even after deleting the initial code

Despite multiple attempts to resolve what I initially thought was a caching issue by completely removing all code from my server, I am still facing the same problem: The default error handling provided by Express Generator in the app.js file contains the ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Slide feature in Drupal Views allows you to create dynamic

This is the design I currently have: https://i.stack.imgur.com/P6spc.jpg For example, when you click on the "Structure" header, it opens up the contents and shows an image. I have created a content type and installed Views. I have separated the image, h ...

What is the proper way to detach an event listener from a class?

I am facing a challenge when trying to remove an event listener. After running the script, I receive an error message stating that changeGirl.off("click") is not a function. Despite this issue, everything else within the code is working perfectly fine. Any ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

What steps can I take to make sure my JavaScript code accurately calculates numbers without resulting in undefined or NaN values?

I'm having an issue with my javascript code for a simple interest calculator. Every time I try to calculate the amount, it keeps returning NaN. It seems like the code is treating the + as if I'm trying to concatenate strings, and I'm not sur ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Encountered an AttributeError problem: The module 'selenium.webdriver' does not contain the attribute 'Chrome'

https://i.stack.imgur.com/VOYXo.pngRecently, I began using Python with Selenium for web automation. However, I've encountered an Attribute error problem. I have successfully installed Python 3.6.5 and the latest selenium packages(selenium-3.11.0) ...

Modal window closed - back to the top of the page

I am struggling with a simple modal popup window that does not maintain the scroll position when closed, instead returning you to the top of the page. I am looking for a way to keep it at the same scroll position without much knowledge of Javascript. You ...