Leveraging JavascriptExecutor for typing and clicking on a specific web element

My goal is to open a link in a new tab and switch to that tab using Selenium in Java with a Firefox browser. I have been successful in opening the link in the same window but am struggling to incorporate sendKeys for my desired action.

WebElement we = driver.findElement(By.xpath("//*[@id='btn']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", we);

The above code worked perfectly for me, however, I am now attempting to use sendKeys as shown below, which is not producing the desired result:

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("keyDown(Keys.CONTROL)
                        .keyDown(Keys.SHIFT)
                        .click(arguments[0])
                        .keyUp(Keys.CONTROL)
                        .keyUp(Keys.SHIFT);", we);

Any suggestions or advice? I am struggling to find the correct syntax for sending keys through JavascriptExecutor. I have tried similar solutions using Actions without success as well.

Answer №1

Here is a code snippet to open any link on a page in a new tab, perform operations there, and then switch back to the original tab for further execution.

WebDriver driver = new FirefoxDriver();
        driver.get("http://stackoverflow.com/");
        WebElement e = driver.findElement(By.xpath(".//*[@id='nav-questions']"));       
        Actions action = new Actions(driver); 
        action.keyDown(Keys.CONTROL).build().perform(); //press control key
        e.click();
        Thread.sleep(10000); // wait till your page loads in new tab
        action.keyUp(Keys.CONTROL).build().perform(); //release control key
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //move to new tab
        driver.navigate().refresh(); // refresh page
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click(); //perform any action in new tab. I am just clicking logo
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //switch to first tab
        driver.navigate().refresh(); 
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click();// refresh first tab & continue with your further work.I am just clicking logo

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

What is the best way to tally the occurrences of a specific object in a list?

I am looking for a way to analyze a list of dates that looks something like this: [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] ...

Using Selenium in Python to find elements that have two different styles specified within the `style` attribute

Struggling to find all elements on the page <i data-visualcompletion="css-img" class="x1b0d499 xep6ejk" style="background-image: url(&quot;https://static.xx.fbcdn.net/rsrc.php/v3/yd/r/A6Wu9TeIieI.png&quot;); background-p ...

The clientHeight property is yielding a result of zero

I'm using JavaScript to create DOM elements dynamically. In order to animate a slide down effect, I need to retrieve the height of a specific div element. However, both clientHeight and offsetHeight are returning 0. I have confirmed that the div eleme ...

Frameworks for Persistent Java Data

I require additional information for a project I'm working on. The application I am developing will interact with a PHP web app, and the media server we are utilizing is extensible in Java. Within the plugin we are creating, I only need limited acces ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

Requesting Access-Control-Request-Headers using jQuery Ajax POST method

I am attempting to send an AJAX request to my server. Initially, I referenced a library (in the web) within a <script> tag in my HTML document and executed it using the following code: $.ajax({ url: api_url + "movie/create", type : "POST", con ...

What are the steps to installing a .deb file offline using Docker?

I am planning to install a .deb file on my Docker container. In my Dockerfile, I execute the following command: RUN apt-get install -y ./fonts/ttf-mscorefonts-installer_3.6_all.deb ROOT Folder |->Dockerfile |->fonts |-> ttf ...

Apply the active class to the initial element within the dynamically generated tabs

Using jQuery, I have created these dynamic tabs. My approach involves selecting the first element, nav + tab content. HTML <div class="col-lg-12"> <div class="tabs-container"> <ul class="nav nav-tabs sys ...

What are some creative ways to incorporate images into SVG paths?

Check out my JSFiddle here. I'm attempting to position this image in the center of my arc. My initial thought was to use .attr("fill","url('somePicture')"), but so far, no luck with that approach. const width = 700; const height = 600; con ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

The output of an Angular factory function is consistently null

I am facing an issue with storing the currentUser object in a factory to make it accessible throughout my app. Despite ensuring that the user object is being received server side, whenever I call CurrentUserFactory.GetCurrentUser(), it returns null inste ...

What is the process for displaying data submitted through a form on page B to page A using Node and Express?

Dealing with the issue Hello everyone. I've been struggling for the past 30 minutes trying to figure out the rendering method problem I'm facing. Whenever I try to post data through a form from Page A and then render that data on Page B, I keep ...

What is the best method for retrieving headers with Selenium?

One of the challenges I'm facing involves navigating to a website and extracting the response headers. Is there a way to achieve this using Selenium? URL obj = new URL(url); URLConnection conn = obj.openConnection(); Map<String, List< ...

Pros and cons of invoking a web API from the client-side

As I embark on creating a web application that integrates with multiple web services, I'd like to hear your thoughts on utilizing javascript to call these services. My Perspective: Advantages: - reduced bandwidth usage (server-side) - eliminates clie ...

Store the input fields of the chosen table row into an array for iterative processing

I need help with extracting input fields from a specific row in a table and adding them to an array. My goal is to loop through this array later. This is how I currently approach it: let selectedTr = []; let arr = []; $('td input:checked').eac ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Error with JavaScript slideshow The slideshow using JavaScript seems to

I'm currently utilizing a script from the WOW Slider (free version) that looks like this: var slideIndex = 0; function showSlides() { var i; slides = document.getElementsByClassName("mySlides"); dots = document.getEle ...

Having trouble with jQuery's getJSON function throwing an error?

I have been working on a project where I am using the getJSON function to fetch JSON data from an API that I am developing. However, I am facing an issue where the getJSON function always triggers the error handler. Below is the JavaScript code I am using: ...

Error encountered: The EVM has reverted the transaction

After successfully deploying this basic smart contract using Remix, I encountered an issue when trying to interact with it through web3.js in my upcoming app. I used the evm version: paris for deployment and everything worked smoothly on Remix IDE. Here i ...

Exploring the power of Mongoose with GraphQL queries

Below is a mongoose Schema I have created: name : String, class : String, skills : [{ skill_name : String }] I want to convert this Schema into GraphQL inputs so that I can save them to MongoDB. Can someone help me with this? Something like: input Stud ...