Is there a way to launch a new tab in Chrome browser using Protractor?

Check out this code snippet (which doesn't open a new tab):

//code to open a new tab in Chrome

browser.actions().sendKeys(protractor.Key.CONTROL +'t').perform();

If we use the following code with 'a', everything works as expected:

//code to select all on the page

browser.actions().sendKeys(protractor.Key.CONTROL +'a').perform();

protractor version 1.3.1

Chrome version 37

ChromeDriver version 2.10

WebDriver version 2.43

Answer №1

If you prefer not to append an element to your DOM, there is another approach you can take:

let url = https://google.com;
return browser.executeScript("return window.open(arguments[0], '_blank')", url);
//This code will open google.com in a new tab (works well with Chrome. Note: tested
// only on Chrome with Protractor).

I have experimented with the above code along with a browser.wait() to determine if the wait is necessary since browser.executeScript() already returns a promise that can be used directly.

Furthermore, I have noticed that even though it appears the browser has shifted focus to the newly opened tab, I encountered difficulties accessing elements within the new tab. To overcome this issue:

browser.getAllWindowHandles().then((handles) => {
    browser.switchTo().window(handles[1]);    //specify the index, assuming only two tabs are open
})

For further insights on window.open(), refer to this article.

Answer №2

There is currently no direct method provided by Selenium to achieve this task, so a workaround is necessary. If you are using Windows or Linux, the CTRL+T shortcut can be simulated as shown below; however, this method did not work for me:

browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('t').perform();

Even when attempting to trigger it on a specific element:

$$('input').first().sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "t"));

The good news is that the following workaround does appear to be effective. You can customize the location.href with the desired URL to open:

browser.driver.executeScript(function() {
  (function(a){
  document.body.appendChild(a);
  a.setAttribute('href', location.href);
  a.dispatchEvent((function(e){
    e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
    return e;
  }(document.createEvent('MouseEvents'))))}(document.createElement('a')));
});

Answer №3

I found this snippet of code to be quite effective when using TypeScript with protractor.

import {browser} from 'protractor';

export class Browser {
  public async openPageInNewTab(url: string) {
    await this.createNewBrowserTab();
    await this.switchToTabNumber(1);
    await browser.get(url);
  }

  public createNewBrowserTab() {
    browser.executeScript('window.open()');
  }

  public async switchToTabNumber(number: number) {
    return browser.getAllWindowHandles().then(function (handles) {
      const newWindowHandle = handles[number];
      browser.switchTo().window(newWindowHandle);
    });
  }

}

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

Guide on instructing ion-slides which slide to display using slideTo

I am facing an issue with a modal that contains an ion-slides element. On the main page, I have thumbnails of images that, when clicked, open the modal with the slider displaying the full-size images. My goal is to make the slider automatically slide to th ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...

Is there a way for me to discover the identity of the victor?

There are 4 divs that move at different, random speeds each time. I am trying to determine which one is the fastest or reaches the goal first. Additionally, there is a betting box where you can choose a horse to bet on. I need to compare the winner with my ...

Edge and Json use a method called "key duplication" to retrieve a specific letter from a given

Encountering an issue specifically on Edge browser when receiving a JSON from the server. Here is the original JSON: {"user":[{"pk":10,"user_group":[1,2,6],"uname":"5555678910","upass":"","first_name":"tutu","last_name":"","country":1,"other_countries":[] ...

Tips for creating a flexible Cell component in react-big-calendar:

Is there a way to make the cell of react-big-calendar flexible depending on the number of events, and enable scrolling? Here is a screenshot showcasing my issue: https://i.stack.imgur.com/K2h69.jpg ...

Error with React's thumbnail component

After integrating the thumbnail component into my project, I encountered an error which is displayed in the image below: https://i.sstatic.net/DGlXZ.png I am seeking assistance with understanding the issue by providing the code from my webpack.config.js ...

The WebSQL encountered an error stating `SQL execution is not permitted` while trying to chain promises

Despite the lengthy title, I couldn't think of a better one for my specific situation. If you have any suggestions, feel free to share! Essentially, I've outlined the issue I'm grappling with in a simplified version on this JSFiddle. In this ...

Getting the (x,y) Coordinate Value from jQuery Script and Saving it as a NSString

div tag is essential for applying bold, italic, and various other formatting options in UIWebview. My goal is to retrieve the position coordinates when a user interacts with the div tag using JavaScript/jQuery. I stumbled upon the required code on JSFiddl ...

Combining photos seamlessly and bringing them to life through animation upon window loading

My main goal is to seamlessly fit the images together, but I'm struggling to achieve this. I tried using masonry, but unfortunately it didn't work for me. All I want is to tightly pack the divs together. For instance, in my fiddle example, I woul ...

Cross-Origin Request Blocked

Attempting to retrieve content using XMLHttpRequest: var url = 'http://mapy.geoportal.gov.pl/wss/service/SLN/guest/sln/woj.json' if (XMLHttpRequest) { var request = new XMLHttpRequest(); if ('withCredentials' in request) ...

React incompatibility causing TextGeometry of Three.js to malfunction

Struggling to incorporate 3D text into my react application using three.js. Unfortunately, the code provided is only resulting in a blank output. This marks my initial venture into Three.js and any assistance would be greatly appreciated. The same code ha ...

Go back to the top of the page while simultaneously refreshing the content

Hi there, I've managed to create a code that smoothly scrolls to the top of the page, but now I'm looking to add a page refresh functionality to it. The current code I have only handles the scrolling part, and I'm not sure how to incorporate ...

The pop-up window is currently inactive

Utilizing the following example, I successfully created a modal window: jsfiddle The modal window allows me to display data from a table. Here is a snippet of my code: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/c ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

How can I make a div disappear when clicked outside of it using JavaScript?

I want to create a scenario where a "form" is only visible after clicking on another "button" under the following conditions: The "form" will only appear if the user clicks on the "button". If the user clicks anywhere outside of the form or clicks the but ...

Selenium is unable to locate the element due to the fact that the page source is written in JavaScript

While attempting to find a specific element on a web page, I noticed that using Inspect Element reveals the HTML code and XPATH, but viewing the page source only displays JavaScript. Any suggestions on how to access the HTML page directly? The page in que ...

Unable to navigate using ui-sref or $state.go in initial directive execution

There seems to be an issue with my ng-repeat on a directive where I'm passing in 3 pieces of information. The directive includes a button that is supposed to pass that information on to another view using params like this: ui-sref='profiles.sho ...

Issues with jqGrid's grid grouping feature not functioning as expected

Is there a way to group my data by the name element and hide the grouping column as shown in this example ()? Even though all 3 columns are present on the page, I specifically want to hide the group column (name). Additionally, it seems that the main col ...