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 best way to assign multiple controllers to a single view in angularJS?

My Attempt: $routeProvider .when('/paintings', { controller: 'imageController' , 'getPaintingImages' templateUrl: 'paintings.html' }) .when('/foods', ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

The instance does not have a definition for the property or method "names" that is being referenced during rendering

Currently, I'm working on developing a CRUD application using Vue.js and Firebase. However, I've encountered an error that I can't seem to resolve: [Vue warn]: Property or method "names" is not defined on the instance but referenced during r ...

Can you explain the purpose of FunctionConstructor in typeScript?

As I delved into the Typescript Ecmascript source code, I stumbled upon this intriguing snippet: interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: st ...

Creating Outer Glow Effect on a Plane Primitive with THREEJS

Seeking guidance on creating a glow effect for a plane primitive in THREEJS. Found examples for cubes and spheres, but those involve encasing the object inside another transparent material, which is not suitable for my needs. The desired glow effect shoul ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

react-widgets: deciding on the return value for the onSearch function in Multiselect

I'm currently experimenting with react-widgets and utilizing the onSearch function in conjunction with the Multiselect component. Even though I can see that onSearch is being called with the searchTerm, I am unable to incorporate the response into the ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

Get rid of any empty space in the image preview icon

Is there a way to eliminate the white space that appears when mixing landscape and portrait images? I want the images to move up and fill the space, even if they don't align perfectly. Additionally, I would like the images to resize based on the scal ...

Which ExpectedConditions should be used when waiting for a text field to appear in Selenium?

Whenever I need to delay the script for a web element (such as a text field or dropdown), I typically use elementToBeClickable: wait.until(ExpectedConditions.elementToBeClickable(By.xpath("someXpath"))) However, I have encountered an issue with a particu ...

Chrome is inaccurately reporting the outerHeight value, while IE and FireFox are displaying it correctly

The jquery.smartWizard plugin includes a function called fixHeight that adjusts the height of a wizard step. It is utilized when displaying a step for the first time or revealing hidden divs within the step. The function works correctly in IE and FireFox, ...

Turn off the autofill option for passwords in Google Chrome

Is there a way to prevent the password autocomplete dropdown from appearing when clicking on the password field? In Chrome Version 61.0.3163.100, none of the solutions seem to be working. Screenshot This issue has been raised many times, but setting autoc ...

When constructing a file directory URL, it is important to utilize the forward slash "/" in the filename

As I am creating a URL, the process involves taking the filename and using it to create a folder with that name. However, an issue arises if the name contains "/", as it causes the URL to break and creates an undesired location. For example: var fileDir ...

Can we expand the capabilities of a ThreeJS object in any way?

In my ThreeJS project, I am implementing an interactive feature where users can click on cubes that behave differently when clicked, such as having different color animations. To achieve this, I plan to create extension classes for the THREE.Mesh object a ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue. Here is my JSP code: <input type="text" name="cantidad ...