Switch Object to WebElement or SearchContext in JavaScript

Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript?

In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` results in an error.

Caused by: java.lang.ClassCastException: com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to org.openqa.selenium.SearchContext

This issue also arises with Shadow Root.

Java Code:

webElemHost = browser.findElement(By.xpath("//tagHere[@id='idHere']"));
strCSSSelector = "#idHere";
JavascriptExecutor js = (JavascriptExecutor) browser;
SearchContext shadowRoot = (SearchContext) js.executeScript("return arguments[0].shadowRoot", webElemHost);
WebElement shadowContent = shadowRoot.findElement(By.cssSelector(strCSSSelector));

JavaScript Code (Not Working):

webElemHost = browser.findElement(By.xpath("//tagHere[@id='idHere']"));
strCSSSelector = "#idHere";
var JavascriptExecutor js = browser as JavascriptExecutor;
var SearchContext shadowRoot = js.executeScript("return arguments[0].shadowRoot", webElemHost) as SearchContext; <== ERROR HERE
var WebElement shadowContent = shadowRoot.findElement(By.cssSelector(strCSSSelector));

Please note that using the getShadowRoot function of findElement is not possible due to limitations in Selenium Version (limited to v3).

Answer №1

If you're working with JavaScript (not TypeScript), remember that there is no need for casting, so make sure you're on the right path.

A better approach would be to access the target element instance within the JavaScript executor by using the querySelector method.

Additionally, since it's JavaScript, element getters are asynchronous, meaning you must use await to wait for the Promise to resolve.

For more information on a similar topic, check out this reference: Similar question reference

Here's an example related to Reddit's shadow-root structure:

const url = "https://www.reddit.com/avatar/shop/product/storefront_nft_01HMZYP9FM37N9ZWVD8C1V9RFH";
await driver.get(url);
const shadowHostElement = await driver.findElement(By.tagName('shop-flow-manager'));
let shadowHost = await driver.findElement(By.js("return arguments[0].shadowRoot.querySelector(arguments[1])", shadowHostElement, 'pdp-partial-generator'));

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

Combining object IDs with identical values to create a new array in JavaScript

i have an array of objects that are a join between the transaction, product, and user tables. I want to merge IDs with the same value so that it can display two different sets of data in one object. Here's my data let test = [ { Transac ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...

Why am I unable to attach this to JQuery?

$("input").keydown(function(event){ if(event.keyCode === 13){ return false; } }); I need to prevent the default action when the "enter" key is pressed in any of my text input fie ...

Endless loop in React Native with an array of objects using the useEffect hook

For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component. To tackle this issue, I have initialized a local state as follows: const [myState, setMyState] = useS ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

Navigating Chrome and chromedriver directories within Jupyter Notebook with Selenium

Scraping a website with a Python notebook using Jupyter has been quite the challenge due to issues with Chrome and chromedriver location. The struggle is real, especially when working on a Linux WSL in a Windows PC. Despite trying various codes, even Selen ...

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

Using JavaScript to implement Gzip compression

As I develop a Web application that must save JSON data in a limited server-side cache using AJAX, I am facing the challenge of reducing the stored data size to comply with server quotas. Since I lack control over the server environment, my goal is to gzip ...

The code snippet $(this).nextAll("#...").eq(0).text("***") isn't functioning as expected

I am experiencing an issue with the following line of code: $(this).nextAll("#status").eq(0).text("Deleted"). I am trying to insert the text "Deleted" in a <span> tag, but it does not seem to be working... Here is my code: admin.php PHP: $sql = "SE ...

Joi mistakenly demanding certain fields that should not be mandatory

I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory. posts valid ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Unusual compilation issue encountered in Vue when trying to use a template for a slot

I encountered a strange issue where my Vue compiler was refusing to render the default named slot of a child component. Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first. Even my VSCode highlighted this problem a ...

From the hue of mossy green to the fiery shade of ruby red,

I managed to create a simple green circle using THREE.Shape. Now, I am interested in changing the color of the circle so that it transitions from green in the middle to red at the border. Although I found an example on this website, I'm struggling t ...

I keep encountering a parse error when trying to parse JSON that contains a numerical key

After receiving data in JSON format from a Java application, I encountered a parse error when the key was of type Long: 1: { "CONGESTION": 1, "ANSWER": 7 } However, after changing the key to a String as shown below: "1": { ...

Printing incorrect value in $.ajax call

I came across this code that I have been working on: var marcas = { nome: '', fipeId: '' }; var marcasVet = []; var select; $.ajax({ dataType: "json", url: 'http://fipeapi.wipsites.co ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...