Using Selenium with Java to Allow Cookies in Shadow DOM

This is the link to my website:

DM :

This is where you can find the locator for accepting all buttons:

 @FindBy( xpath = "//button[@data-testid = 'uc-accept-all-button']")
    WebElement cookies;

This snippet shows some HTML code:

I am using Selenium 4 and Java. I attempted a solution like this one:

public void acceptAllCookies( ) {

        cookies = driver.executeScript("return document.querySelector('#usercentrics-root').shadowRoot.querySelector("cookies")");
        cookies.click();
    }

Unfortunately, the above solution did not work as expected and resulted in an error message:

If anyone could offer assistance, it would be greatly appreciated. As a beginner, I am encountering this issue for the first time.

I even tried adding additional quotation marks based on a solution I found here, but ended up getting the entire executeScript command as text.

Answer №1

To ensure proper decoding, it is essential to incorporate escape sequences when dealing with sensitive data such as "cookies". Take a look at the example below:

cookies = driver.executeScript("return document.querySelector('#usercentrics-root').shadowRoot.querySelector(\"cookies\")");

Answer №2

If the css selector is 'cookie' and not a Java variable, you must use single quotes around it in the js.executeScript method. The WebElement defined as Cookie above cannot be directly used when calling executeScript.

cookies = driver.executeScript("return document.querySelector('#usercentrics-root').querySelector(button[data-testid = 'uc-accept-all-button'])");

If this solution does not resolve your issue, please provide more details about the problem.

Answer №3

The "Accept All" button can be found within a shadow root environment.


Resolution

In order to interact with the specified element, utilize the querySelector() method along with various locator strategies:

driver.get("https://www.dm.rs/?wt_mc=sea.google.ads_generic.15146192844.132927670207.558370268562");
Thread.sleep(5000);
WebElement element = driver.findElement(By.cssSelector("#usercentrics-root"));
SearchContext context = element.getShadowRoot();
WebElement cookieAcceptAll = context.findElement(By.cssSelector("button[data-testid='uc-accept-all-button']"));
cookieAcceptAll.click();


Related Resources

You may refer to the following informative discussions:

  • A guide on automating shadow DOM elements using selenium
  • Locating elements within #shadow-root (open) with Selenium4 and Java

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

Sending the name of a table as a parameter for a prepared statement

I'm currently working on mastering the integration of MySQL with Java, specifically struggling with prepared statements. Within my MySQL database, I have a table named "temp" which holds the following values (directly extracted from the MySQL console ...

I encountered an error in the Expo dashboard when attempting to upgrade from version 48 to 49 during the Expo Expo version change

For the image description, type in: "expo": "49", "react-native-reanimated": "~3.3.0", "expo-updates": "~0.18.19" I need assistance, can someone please help me out? ...

Utilizing Q for Node.js promise handling

I am currently working on a Node application where I need to utilize promises for handling asynchronous calls. Although I have a foreach loop inside a .then(function()) of a promise, I am facing an issue where I am unable to return the final result of the ...

Allow the mobile web app to prompt the user's default mobile browser to open a link rather than displaying it within the app itself

After developing a mobile web app for Android and iOS, I successfully installed the apk and ipa files on my test phones. Unfortunately, I encountered an issue when attempting to open an external link that is supposed to open in the user's default bro ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Use javascript to implement lazy-loading for images

Looking to enhance website performance by lazy loading images. Plan is to initially display a set number of images and then load the rest lazily. Here's what I have currently: Check out the code here <div> <img src="http://i.imgur.com/CmU ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Using `texture.needsUpdate = true` in Three.js can cause significant performance issues due to its slow execution

I am currently working on a project involving a Three.js scene where I need to update textures after a certain period of time. However, I have noticed that updating the textures is causing a significant slowdown in the FPS, dropping it to 1-2 FPS for sever ...

`Inefficient functioning of Selenium Webdriver: Identifying the Issue`

I wrote a program designed to log in to TextNow, sign in, and call any number efficiently. However, when I run the script, everything works except for the final functionality. I am unsure of where the mistake lies, so I would appreciate any guidance or sol ...

What is the best way to activate an API call in a React Modal only when the Modal is displayed

I have been assigned a project to create a proof of concept web application using REACT in my organization. The application includes a table displaying various issues, with each issue having a button that, when clicked, opens up a modal. The modal then fet ...

CRITICAL ISSUE: Mark-compact processes not performing effectively close to heap capacity

I encountered an error and I'm seeking a brief explanation to help me understand what needs to be fixed. This error occurs during the compilation of TypeScript. <--- Last few GCs ---> [1791:0x5533880] 72626 ms: Scavenge (reduce) 2042.8 (2 ...

PHP encoding a multidimensional associative array into JSON and passing it to JavaScript

Greetings, initially my array had this structure: PHP $results = array( "banana" => $bananavalue, "apple" => $applevalue, ); echo json_encode($results); JS var fruits = []; $.ajax({ type: "POST", url: "actions/MYphp.php", data: Pass ...

jQuery text slideshow not working properly when a <br> tag is present

I'm looking to develop a basic text slideshow that smoothly transitions between phrases and loops continuously. However, I've run into an issue where the slideshow malfunctions when I add a line break in the text. It only seems to work properly w ...

The Jade variable assignment variable is altered by the Ajax result

Seeking a solution to update a Jade variable assigned with the results of an ajax post in order for the page's Jade loop to utilize the new data without re-rendering the entire page. route.js router.post('/initial', function(req, res) { ...

Struggling to incorporate a new attribute into an object

Whenever I attempt to insert a new field into an object, it seems to overwrite all existing fields with the new one instead of simply adding it. data.collection.updateOne({},{$set: {"object": {"hi":0}}},true) My Desired Outcome: object ...

Challenge with JSON stringification and JSON decoding

Looking at the HTML code: <input type="hidden" name="test[]" id="test" value= "" /> For the JavaScript part: jQuery(document).on('click', '#target', function () { var jsArr = ["val1", "val2", "val3"]; jQuery('input ...

Tips on organizing <li> elements inside divs with ng-repeat

Currently, I am utilizing ng-repeat to loop through an array and create <li> elements. However, my goal is to group every 2 li elements within a div. <li ng-repeat="item in items">{{item.name}}</li> The desired output format should look ...

Is there a way to boost the slides limit and make it dynamic? As of now, it's restricted to just

I am looking to achieve the same fadeIn and fadeOut effect as demonstrated in the example below: However, the issue I'm facing is that this example was designed for only 3 slides and I need more than 3 slides or the ability for it to dynamically incr ...

What is the best way to add timestamps to derivative posts or comments related to a post?

Currently working on a tutorial and I think it would be great to timestamp comments as well. For the main posts, the timestamp works fine, but not for the child posts or comments as we can call them for simplicity. Since I am using Firebase, I'm uns ...

I want to show error messages using jquery only when the username or password is entered incorrectly. How can this be achieved?

document.getElementById("buttonClick").addEventListener("click", mouseOverClick); function mouseOverClick(){ document.getElementById("buttonClick").style.color = "blue"; } $("#buttonClick").hover(function() { $(this).css('cursor',&apos ...