Using Selenium Webdriver to simulate pressing ‘ctrl + t’ for opening a new tab in Javascript

I have been utilizing Selenium Webdriver to conduct testing on a web application that is currently undergoing development. Despite having developed multiple tests already, I am facing challenges in attempting to open new tabs within the window controlled by Selenium. After exploring numerous solutions, most of which are geared towards Java or Python (and not applicable to my Javascript requirements), I have yet to achieve success.

Here are some key details:

Selenium Webdriver: v.3.1.0 OS: Xubuntu 16.04 Browsers: Chrome 55.0.2883.87 and Firefox 50.1.0

Various solutions I have tried include:

  • Utilizing action sequences, which were ineffective in both Chrome and Firefox, with Firefox generating an error:

    driver.actions().keyDown(Key.CONTROL).sendKeys('n').keyUp(Key.CONTROL).perform();

  • Experimenting with Key.chord(), resulting in silent execution but producing unexpected charCodes in Firefox:

    driver.findElement(By.css("body")).sendKeys(Key.chord(Key.CONTROL, 't'));

  • Restricting usage to Key.CONTROL alone, leading to successful key inputs but again displaying unusual charCodes in Firefox:

    driver.findElement(By.css("body")).sendKeys(Key.CONTROL + "t");

My current approach involves directing the driver to a webpage equipped with javascript keypress detection, verifying if the keys were triggered after inputting 'aaa':

driver.get("http://unixpapa.com/js/testkey.html");
driver.findElement(By.css("body")).sendKeys("aaa");
driver.findElement(By.css("body")).sendKeys(Key.CONTROL + "t");

This action results in the following output displayed on the page's detection area:

keydown  keyCode=17        which=17        charCode=0        
keydown  keyCode=84  (T)   which=84  (T)   charCode=0        
keypress keyCode=116 (t)   which=116 (t)   charCode=116 (t)  
keyup    keyCode=84  (T)   which=84  (T)   charCode=0        
keyup    keyCode=17        which=17        charCode=0  

Although it indicates keystrokes have been detected, no response is elicited and no additional tabs are created. Absence of errors, warnings, or notifications has left me uncertain whether this issue stems from a bug, a configuration misstep, or any other potential factor. Any insights or suggestions would be greatly appreciated for resolving this dilemma.

Answer №1

If you want to open a new tab, you can attempt the following method:

driver.executeScript('window.open();');

Answer №2

If you want to try something new, consider utilizing the Robot Class with the following example:

   Robot robot = new Robot();
   robot.keyPress(KeyEvent.VK_CONTROL);
   robot.keyPress(KeyEvent.VK_T);
   robot.keyRelease(KeyEvent.VK_CONTROL);
   robot.keyRelease(KeyEvent.VK_T);

Answer №3

private void launchNewTab(String websiteURL) {
        ((JavascriptExecutor) driver).executeScript("window.open('" + websiteURL + "','_blank');");
    }

Call this function to initiate a new tab opening with the specified URL.

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

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Encountered error while trying to select a country with Selenium and Python: UnexpectedTagNameException - Select function only works on <select> elements, not <div>

My goal is to extract the data from an iterative scatter plot, but first I need to change the country on the website. However, I am encountering issues with selecting the desired country. Website link: The error message displayed is --------------------- ...

What is the process for sending a POST Request to Ghostbin using Node.JS?

I'm attempting to make a POST request to Ghostbin using Node.JS and the request NPM module. Below is the code I have been utilizing: First Try: reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) ...

Ways to determine the length of a string that includes zero or negative width characters such as u0007 or 

Consider the following scenario: I have a string 'aa\b\u0007\u0007' var myString = 'aa\b\u0007\u0007'; console.log(myString); //=> 'a' (plus 2 beeps) console.log(myString.length); //=> 5 ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

My hosting provider is not allowing the Express server to serve static files

I am facing an issue where my Express.js app is serving my js file locally, but on my hosting platform, I am unable to access the js file. var express = require("express") var app = express() var path = require("path") var bodyParser = ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

When attempting to render 2 components based on the results of 2 fetch calls using Promise.allSettled(), I encounter difficulties if one of them throws an error

I have encountered an issue while using Promise.allSettled() in sending two fetch calls. I am rendering components based on the result - a component with data if it is fulfilled and an error component if rejected. However, when one of the fetch calls throw ...

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

Look up smartphones, select a specific model, and display a specific product review on the console

While attempting to extract and print a specific review of a mobile product from Amazon using Selenium with Java within the Cucumber framework, the output in the console appears to be blank. @Then("Click on the add to cart button") pu ...

Handle empty response from endpoint response

I'm facing an issue with a method that subscribes to an endpoint for a response. In some cases, the endpoint returns null and I need to handle this scenario. public list: Array<any>; this.GetList(this.getListRequest) .subscribe( (resp) =& ...

Problem with TypeScript involving parameter destructuring and null coalescing

When using parameter destructuring with null coalescing in TypeScript, there seems to be an issue with the optional name attribute. I prefer not to modify the original code like this: const name = data?.resource?.name ?? [] just to appease TypeScript. How ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

There is an issue occurring with Minium involving glue and the browser

Can anyone explain why Minium (Selenium Webdriver Java + Cucumber) is generating this error trace? I've been trying to troubleshoot for hours, but nothing seems to resolve this issue. Project Structure https://i.stack.imgur.com/aqbGA.png Java: im ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

Tips for managing an event using the bxSlider callback API

I am currently using bxSlider to create a slideshow on my website. However, I now want to implement a manually controlled slideshow that also displays text content related to each image below the slideshow: Here is the code I have so far: <!--SlideSho ...