how to open a new tab using JavaScript with Selenium

My code is supposed to open a new window that goes from the login window to the main menu, module, reports, and finally the report name. The report name should be opened in the next tab.

Issue: The report name is not opening in a new tab; it's opening in a new window (blank window). Due to IE expiration within the organization, it redirects to Edge as per the legacy app code. We are not using a separate driver folder for this setup. Java - JDK 1.8 Selenium - 3.141.59 Tool - IntelliJ




   public void launchBrowser() throws IOException {
      String browser = properties.getProperty("Browser");
      if (browser.equalsIgnoreCase("chrome")) {
//       System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");

         System.setProperty("wdm.proxy", wdmProxy);
         System.setProperty("wdm.proxyUser", wdmProxyUser);
         System.setProperty("wdm.proxyPass", wdmProxyPwd);
         WebDriverManager.chromedriver().setup();
         genericSteps.driver = new ChromeDriver();
      } else if (browser.equalsIgnoreCase("ie")) {
//       System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe");
         DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
         capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);

         System.setProperty("wdm.proxy", wdmProxy);
         System.setProperty("wdm.proxyUser", wdmProxyUser);
         System.setProperty("wdm.proxyPass", wdmProxyPwd);
         WebDriverManager.iedriver().setup();
         genericSteps.driver = new InternetExplorerDriver(capabilities);
         genericSteps.driver.manage().window().maximize();
         genericSteps.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         String test = properties.getProperty("URL");
         genericSteps.driver.get(test);
      }else if (browser.equalsIgnoreCase("edge")) {
//       System.setProperty("webdriver.ie.driver", "./Drivers/IEDriverServer.exe");
//       System.setProperty("webdriver.edge.driver", "./drivers/DriverServer.exe");

//       System.setProperty("webdriver.edge.driver", "C:\\Users\\-------\\app\\drivers\\msedgedriver.exe");
         EdgeOptions capabilities = new EdgeOptions();

         System.setProperty("wdm.proxy", wdmProxy);
         System.setProperty("wdm.proxyUser", wdmProxyUser);
         System.setProperty("wdm.proxyPass", wdmProxyPwd);
         WebDriverManager.edgedriver().setup();
         genericSteps.driver = new EdgeDriver(capabilities);
         genericSteps.driver.manage().window().maximize();
         genericSteps.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         genericSteps.driver.switchTo();
         String test = properties.getProperty("URL");
         genericSteps.driver.get(test);

      }
   }

   /* Explicit wait for the Webelement on the page to be visible */
   public void explicitWait(WebElement element, int timeToWaitInSec) {
      WebDriverWait wait = new WebDriverWait(genericSteps.driver, timeToWaitInSec);
//    wait.until(ExpectedConditions.visibilityOf(element));
   }

   /* Explicit wait for the Webelement on the page to be visible */
   public void expliciteWaitVisiblityOfWindows(int timeToWaitInSec) {
      WebDriverWait wait = new WebDriverWait(genericSteps.driver, timeToWaitInSec);
      wait.until(ExpectedConditions.numberOfWindowsToBe(2));
//    wait.until(ExpectedConditions.titleIs(pageTitle));
   }


public void clickByElement(WebElement element) throws IOException {
      explicitWait(element, 120);
      if (element.isDisplayed()) {
         element.click();
         waitForPageToLoad(90);
      }
}



public void clickByElementJavaScript(WebElement element) throws IOException {
      JavascriptExecutor executor = (JavascriptExecutor)genericSteps.driver;
      executor.executeScript("arguments[0].click();", element);
}




public void verifyTitle(String title) throws IOException {
      genericSteps.driver.getTitle();
}

public void explicitWait1(WebElement element, int timeToWaitInSec) {
      WebDriverWait wait = new WebDriverWait(genericSteps.driver, timeToWaitInSec);
      wait.ignoring(StaleElementReferenceException.class);
      wait.until(ExpectedConditions.elementToBeClickable(element));
}

public void mouseOverByElement(WebElement element) throws IOException {
      explicitWait(element, 1000);
      new Actions(genericSteps.driver).moveToElement(element).build().perform();
}

public void mouseOverToSelectElement(WebElement element, WebElement element1) throws IOException {
      explicitWait(element, 30);
      Actions action = new Actions(genericSteps.driver);
      action.moveToElement(element).moveToElement(element1).click().build().perform();

}


/*
* This method will switch windows using the page title
*
* @param get the title of the page
*/

public boolean switchToWindowByTitle(String title) throws Exception {
      ((JavascriptExecutor) genericSteps.driver).executeScript("window.focus();");
      ((JavascriptExecutor) genericSteps.driver).executeScript("window.focus();");
      Set<String> availableWindows = genericSteps.driver.getWindowHandles();
      System.out.println("HELLO");
      if (!availableWindows.isEmpty()) {
         for (String string : availableWindows) {
            System.out.println("HELLO" + genericSteps.driver.switchTo().window(string).getTitle());
            genericSteps.driver.manage().window().maximize();
            waitForPageToLoad();
         }

         for (String windowId : availableWindows) {
            String switchedWindowTitle = genericSteps.driver.switchTo().window(windowId).getTitle();
            waitForPageToLoad();
            if ((switchedWindowTitle.equals(title)) || (switchedWindowTitle.contains(title))) {
               System.out.println(switchedWindowTitle);
               return true;
            }
         }
         Thread.sleep(3000);
         waitForPageToLoad();
      }
      return false;
}


public void switchToWindowByTitleNew(String title) throws Exception {
      ((JavascriptExecutor) genericSteps.driver).executeScript("window.focus();");
      ((JavascriptExecutor) genericSteps.driver).executeScript("window.open();");

      Set<String> availableWindows = genericSteps.driver.getWindowHandles();
      System.out.println(availableWindows.toArray().length);
      if (!availableWindows.isEmpty()) {
         for (String string : availableWindows) {
            System.out.println("HELLO" + genericSteps.driver.switchTo().window(string).getTitle());
            genericSteps.driver.manage().window().maximize();
            genericSteps.driver.navigate();

            waitForPageToLoad();
         }

         for (String windowId : availableWindows) {
            String switchedWindowTitle = genericSteps.driver.switchTo().window(windowId).getTitle();
            waitForPageToLoad();
            if ((switchedWindowTitle.equals(title)) || (switchedWindowTitle.contains(title))) {
               System.out.println(switchedWindowTitle);
               return;
            }
         }
         Thread.sleep(3000);
         waitForPageToLoad();
      }
}
//Mahi added

public boolean switchToTabByTitleNew(String title) throws Exception {
      ((JavascriptExecutor) genericSteps.driver).executeScript("window.focus();");
      Set<String> availableTabs = genericSteps.driver.getWindowHandles();
      System.out.println(availableTabs.toArray().length);
      if (!availableTabs.isEmpty()) {
         for (String string : availableTabs) {
            System.out.println("HELLO" + genericSteps.driver.switchTo().window(string).getTitle());
            genericSteps.driver.manage().window().maximize();
            genericSteps.driver.navigate();

            waitForPageToLoad();
         }

         for (String windowId : availableTabs) {
            String switchedTabTitle = genericSteps.driver.switchTo().window(windowId).getTitle();
            waitForPageToLoad();
            if ((switchedTabTitle.equals(title)) || (switchedTabTitle.contains(title))) {
               System.out.println(switchedTabTitle);
               return true;
            }
         }
         Thread.sleep(3000);
         waitForPageToLoad();
      }
      return false;
}

 public void handleSSLError() throws Exception {
      String title = genericSteps.gerDriver().getTitle();
      System.out.println("The value of title is "+ title);
      if(title.equalsIgnoreCase("This site isn’t secure"))
      {
         clickByElementJavaScript(genericSteps.gerDriver().findElement(By.id("overridelink")));
         waitForPageToLoad();
      }
   }



Answer №1

Have you considered trying the following approaches?

Option 1:

  const commandControl = platform.indexOf('darwin') !== -1 ? Key.COMMAND : Key.CONTROL

  WebElement linkElement = driver.findElement(By.id("link_element_id"));

  await driver.actions()
    .move({ origin: clickable })
    .pause(1000)
    .keyDown(commandControl)
    .sendKeys(Key.ENTER)
    .keyUp(commandControl)
    .perform()

Option 2:

  driver.findElement(By.linkText("urlLink")).sendKeys(Keys.chord(Keys.CONTROL,Keys.RETURN)); 

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 appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

There is an unbound local error popping up in the script I created using Selenium for my user

I am facing an issue with a program that scrapes data from a web app. The program is running fine on my computer, but the user keeps encountering an unbound local error in the box_input method. Here is the error screenshot sent by the user. I'm unsur ...

Encountering a theme issue in the makeStyles function within Material-UI version 5

While working on some React components, I created a styles.js file for each of them. I am following a YouTube tutorial that uses material-ui version 4, so I decided to upgrade to V5. Code snippet for the component (Form): import React from 'react&apo ...

Error: The value of 'v4' property is not defined and cannot be read

I am encountering an issue with Vue.js: vue.esm.js?efeb:628 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'v4' of undefined" found in ---> <AddTodo> at src/components/AddTodo.vue <App> at src/Ap ...

"The integration of Appium and Selenium for monitoring app activity and app package alterations during the login process on the Microsoft Azure

Upon launching our app, the default MS login screen appears for user authentication. However, when using Appium (Selenium with JAVA), the app launches successfully but fails to identify any elements once the MS login screen is displayed. Printing the app a ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this: {“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547} My task is to encode this data into a hex message. Bel ...

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

What is the method for determining the numerical worth of the px containers?

https://i.stack.imgur.com/0K2TD.png Total width of the bar is set to 500px, with the red box at a width of 150px, the yellow box at 200px, and the green box at 50px. CSS Styles: .box { float:left; width:150px; box-shadow:3px 3p ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Is it safe to set content type as text/plain instead of application/json for JSON response?

I've been developing a PHP script to retrieve public JSON data, which will be accessed by JavaScript on the client side. However, I've encountered an issue with the server (LiteSpeed shared hosting) not having brotli/gzip compression enabled for ...

Why is the value in my React Redux state not updating as expected?

I recently started learning react js as a beginner. To practice, I created a crud app and integrated firebase for authentication. However, I'm facing an issue where I'm not able to retrieve the updated value. Index.jsx At line 11, I'm stru ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Tips for sending an ID to a path link in React Js

Can anyone assist me in setting up a path for a component like this "/products?id=uniqueId" in my React Js Project? The unique id is retrieved from the database and varies depending on the product chosen. Below is an excerpt of my code: CodeSandbox App.j ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Creating Interactive Graphs with HTML and JavaScript: A Guide to Dynamic Graph Drawing

I am seeking to create a dynamic graph using standard HTML, JavaScript, and jQuery (excluding HTML5). The nodes will be represented by divs with specific contents, connected by lines such as horizontal and vertical. The ability to add and remove nodes dyn ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

Trigger a fire event upon entering a page containing an anchor

My query is similar to this particular one, with slight differences. I am working on a page that includes an anchor, such as page.html#video1. Within this page, there are multiple sections identified by ids like #video1, #video2. Each section comprises of ...

Combine all the HTML, JavaScript, and CSS files into a single index.html file

So here's the situation - I am utilizing a C# console application to convert four XML files into an HTML document. This particular document will be circulated among a specific group of individuals and is not intended to be hosted or used as a web app; ...