Incapable of dealing with Shadow Element

Despite my efforts, I have been unable to successfully print the text from a nested shadow element using the code below. When attempting to execute the same code through the console window, it works as expected.

https://i.sstatic.net/Jlek1.png

Here is the code snippet:

import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ShadowRoot {
    public static void main(String[] args) throws InterruptedException {


        WebDriver driver;
        ChromeOptions chromeOptions = new ChromeOptions();

        chromeOptions.addArguments("--remote-allow-origins=*", "ignore-certificate-errors");
        driver = new ChromeDriver(chromeOptions);

        // Set browser type and chromedrover.exe path as parameters
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        String url = "http://watir.com/examples/shadow_dom.html";
        driver.get(url);
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //      js.executeScript("document.querySelector('#shadow_host').shadowRoot.querySelector('input').value='username'");
        js.executeScript("document.querySelector('#shadow_host').shadowRoot.querySelector('#nested_shadow_host').shadowRoot.querySelector('#nested_shadow_content > div').innerText");

        Thread.sleep(10000);

        driver.close();
    }
}

https://i.sstatic.net/KxNmt.png

Answer №1

Your code snippet

document.querySelector....innerText
appears to only be retrieving the value without taking any further action. To display the value in the browser console, you should enclose it within console.log().

js.executeScript("console.log(document.querySelector('#shadow_host').shadowRoot.querySelector('#nested_shadow_host').shadowRoot.querySelector('#nested_shadow_content > div').innerText)");

Answer №2

If using selenium, the return type is a webelement. To retrieve the value, you can utilize either .getText() or .getAttribute().

JavascriptExecutor js = (JavascriptExecutor) driver;

WebElement shadowElement=js.executeScript("return document.querySelector('#shadow_host').shadowRoot.querySelector('#nested_shadow_host').shadowRoot.querySelector('#nested_shadow_content > div')");
System.out.println(shadowElement.getText());
System.out.println(shadowElement.getAttribute("textContent"));
System.out.println(shadowElement.getAttribute("innerText")); 

Alternatively, inline code like this should be effective:

System.out.println(js.executeScript("return document.querySelector('#shadow_host').shadowRoot.querySelector('#nested_shadow_host').shadowRoot.querySelector('#nested_shadow_content > div')").getText());

Or:

System.out.println(js.executeScript("return document.querySelector('#shadow_host').shadowRoot.querySelector('#nested_shadow_host').shadowRoot.querySelector('#nested_shadow_content > div')").getAttribute("textContent"));

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

Moving an object from one container to another using the draggable feature

I have successfully implemented a feature that allows an element to be dragged from one container to another. However, a new issue has arisen. Once the element is dropped into the second container, it is no longer draggable within the same container. $( ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

Can a web application access USB devices across different browsers and operating systems?

I am curious about how we can achieve this particular task. I have heard various things about Silverlight 4, JavaScript, or ActiveX control, but I have yet to see a demonstration of code for any of them. Is there a web component available for this, or is ...

A step-by-step guide on resolving the number type coerce error 50035 that occurs during command registration

I am delving into the world of creating a discord bot, and it has been a while since my last project using slash commands. However, I encountered an issue while trying to register my commands: DiscordAPIError[50035]: Invalid Form Body application_id[NUMBER ...

Displaying data in a Vue list using key-value pairs

Can the key value be displayed in the component when passing it in the list? The data is structured like this: { id: 1, title: "test", text: "Lorem ipsum doloret imes", date: "20-01-2020" }, { id: 2, title: "tes", text: "Lorem ipsum doloret ...

What are the correct steps for utilizing moment.js to modify the format of a timestamp?

Within my data.json file, I have a date stored in a long format. "start_time" : "1435377480000" To convert this long format into an actual date format, I am looking to utilize the power of moment.js. This is what I have attempted st ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Third Party Server Integration for Android Apps

As a first-year computer science student with a limited knowledge of Java, I am attempting to create an Android app. My app is at a basic stage, and I now want to send location data from one device to other devices that have the app installed. Although I ...

Locate the class ID and refine the search results by another class

I am currently working on a task that involves extracting the first <li> element's id where it has the class name my_class, and checking if the <span> with the class Time contains a ":" using jquery. Below is the sample HTML structure: & ...

Transmit an image to a server using JavaScript fetch functionality

I've decided to switch up my form submission process and make it more seamless by utilizing fetch. When it comes to handling the input image value: <input name="perfil" type='file' id="imageUpload /> And then, to stor ...

Information not displaying correctly on the screen

My latest project is a recipe app called Forkify where I am utilizing JavaScript, npm, Babel, Webpack, and a custom API for data retrieval. API URL Search Example Get Example The app displays recipes with their required ingredients on the screen. Addit ...

Fetching data dynamically from the server using AJAX for a interactive chart with Flot

After looking at the Flot reference, they mentioned, The plot function can also be used as a jQuery chainable property. Is it possible to configure the Flot chart in this way? var pid = ''; var kid = ''; var chartasset; $(documen ...

Troubleshooting issue with JavaScript's flatMap() method encountering NaN result during element operation

Hey there, I have a simple query that's giving me some trouble. My goal is to flatten an array with a single layer of depth while also multiplying each element by 2. However, when I attempt to utilize flatMap on arr1, the output in the console display ...

I'm currently attempting to retrieve information from an Excel spreadsheet and input that data into the login and password fields. Unfortunately, I encountered an error during the process

Issue: An error occurred during the execution of test case "cptoadsLogin". The data provider is attempting to pass 2 parameters, but the method "com.toads.Script.LoginDemo#cptoadsLogin" does not accept any parameters. This resulted in a TestNGException ...

What is the best way to retrieve the most recent value in a MongoDB aggregation?

In my collection, some documents have a status field while others do not. However, all documents contain a data field. I am trying to construct a query that retrieves the most recent values for both fields. The issue arises when using the $last operator, a ...

Unable to execute mobile emulation on a custom device

When running testcases in different mobile views, I encountered an issue while trying to run tests in mobile emulation mode using Google Chrome. The test cases work fine when selecting a device from the existing list, but when attempting to create a custom ...

Ways to ensure that ng-view stays idle until an XHR response is received

Is there a way to make the ng-view wait for an xhr request? I have two controllers set up for a routed ng-view - the first one loads perfectly, but the second one doesn't render properly because the xhr response is happening after partial.html has bee ...

"Using Node.js for proxying requests and implementing OAuth authentication

Having a small node.js application that relies heavily on oAuth, I encountered an issue: the server where I intend to install it is concealed behind a proxy. This necessitates rewriting a portion of the code to incorporate proxy usage. Here's my query ...

Updating a specific field in a document using Node.js and MongoDB

Hey, I'm a beginner in nodeJS and I could use some help. I've been able to update an entire document easily but I'm struggling to update just a single value. Here's my code: router.patch("/:id", async (req, res) => { console.log(re ...

Switching icon with jQuery upon clicking

I'm just starting to learn jQuery and I'm working on changing the font icon class when clicked to display a drop down. Right now, it changes the icon and drops down the content as expected. However, I'm facing an issue where I want the icon ...