Opening a link in new window - java

I need to open a link in a new window with Selenium. I found the following 2 (assume we is the WebElement and I have already found it and myWait just performs a wait for x milliseconds):
1)
Actions act = new Actions(driver);
act.contextClick(we).perform();
myWait(1000); // allow the menu to come up
act.sendKeys(which).perform();
2)
we.sendKeys(Keys.CONTROL + "t");
In #1 I see the menu come up, but the sendKeys does not work (oh, by the way the "which" in sendKeys is a "t"). In #2 it simply ignores it.
In #1 is the menu that comes up in a new window already? Do I have to driver.switchTo()? or if not, what am I doing wrong?
Also, is there another way to do this? we is an element of form <a href=blah> and a regular click opens fine.

You can try the below code to open a link in a new window:
Actions newTab= new Actions(driver);
WebElement link = driver.findElement(By.xpath("//xpath of the element"));
//Opening the link in new window
newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Note: After you've opened the link a new window, to get control of it, you need to get the handle of this child window, switch to it using driver.switchTo.window("childwindowhandle") and take further actions. And, after that you can close it and switch back to the Parent window(original one) and take actions here (Make sure to get the parent window handle before you open the link in a new window, so that switching back to it is easier).

Related

Cant click on the right click menu during automation as it is outside the DOM

I'm trying to automate a test for which I need to search a movie, right-click on a link and select the first option (open in new tab).
Have tried initiating a robot class, using the action class, treating the right-click selection window as a separate window, and even sending a "shift+enter" command after selecting the link. None of it worked.
the most popular solution (the action class) had the problem that even though I was able to right-click the link by, using a context-click when I gave the command to "press the down key of the keyboard" instead of moving into the right-click menu, it scrolled by webpage down, i.e. it did not interact with the menu at all. Although when I manually click the down button, it obviously selects the first option of the menu. (Have tried multiple Keys.DOWN commands as well)
Here's my action class code:
driver.get("https://www.google.com");
WebElement search = driver.findElement(By.name("q"));
search.click();
search.sendKeys("After life"+ ENTER);
WebElement toClick =driver.findElement(By.xpath("//h3[contains(text(),'After Life (TV Series 2019–2022) - IMDb')]"));
Actions actions = new Actions(driver);
actions.contextClick(toClick).perform();
actions.sendKeys(Keys.DOWN).sendKeys(ENTER).perform();
Maybe is makes sense to get "href" attribute, open a tab manually and go to the link on the new tab?
I am not sure why it is not working with Actions class and I assumed you are using Keys.DOWN instead of keys.ARROW_DOWN. Even it is also not working with keys.ARROW_DOWN. By using both Actions and Robot classes it worked.
Code:
Actions actions = new Actions(driver);
actions.contextClick(toClick).perform();
Thread.sleep(2000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Handling right click menu items in selenium java

I want to right click and go the 5th option that is "copy link address".
I have tried the following code and this is the only thing i could i could find on then internet
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
TimeUnit.SECONDS.sleep(2);
actions.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
This code actually scrolls the page downward instead of moving down the right click menu as if the right click menu was never there.
Using context clicks is not something I would recommend as it violates Parallel Testing Best Practices
The tests need to be small, atomic, and autonomous and your current approach assumes that the browser has to be in focus. It means that you will neither be able to do anything while the test is running nor run the tests in parallel.
So instead I would suggest:
Extract href attribute from the link you want to click
Use JavascriptExecutor and Window.open() function in order to open the link in the new tab
Switch to the new tab
Example code:
WebElement link = driver.findElement(By.xpath("//*[(#id = \"u_0_1n\")]"));
String url = link.getAttribute("href");
driver.executeScript("window.open('" + url + "');");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));

Selenium is unable to find element in a Modal window with iframes

I have a page in which I click on a link which opens a new Modal window which has an iframe. I switched to the iframe and performed some validation, then click on the link in that Modal window which in turn opens a second new Modal window with an iframe. I am facing issue clicking on any element in that second new Modal window.
Here is my code.
WebElement Hotelname = driver.findElement(By.cssSelector(".hotelTitleZone2>a"));
Hotelname.click(); \\This will open a new Pop up.
driver.switchTo().frame(1);
\\perform some validation
String parentHandle = driver.getWindowHandle();
driver.findElement(By.linkText("View on a Map")).click(); \\This will open second pop up Modal window
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
driver.switchTo().defaultContent();
driver.switchTo().frame(1); \\switching to frame
driver.findElement(By.linkText("Close")).click();
When I am running this code, I am getting an error:
org.openqa.selenium.NoSuchElementException: Unable to locate element:
{"method":"link text","selector":"Close"}
I tried with or without switching to default content, without switching to frame in second Modal window but result is always the same.
Any help is appreciated ? Thanks.
My understanding is:
start from the default window
click to open the first Modal window that has an iframe
Switch to this new iframe (index = 1)
Get the ID for the current window handle, which is the default window handle
click to open the second Modal window that has a second iframe
switch to the second Modal window
switch back to the default window
switch to iframe (index = 1)
Find the button you are after
There are a few confusions here:
in step 4 above, you used String parentHandle = driver.getWindowHandle(); to store the original default window handle but you have never used it, instead, you use driver.switchTo().defaultContent();
What happened to the first Modal window after you clicked it? Did it close? if it had not closed, its iframe would still be iframe (index=1), this would explain why you could not find your button from the iframe (index=1); as your button would reside on the iframe that belongs to the second Modal window, which is likely to be iframe (index=2). You may use driver.switchTo().frame(2); to address it instead. To be sure, you can inspect HTML elements to see how many iframes are present and to which Modal windows they belong to.
Hope you will find it useful.

Switch between browser tabs using Selenium WebDriver with Java

I need to switch between the browser tabs, used the following code,
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
It was working properly sometimes only, but sometimes it is showing an exception.
Can anyone suggest me is there any other instructions for switching tabs within a single window by using java.
You have to use window handle function here. Here is a sample working code in java:
String parentHandle = driver.getWindowHandle(); // get the current window handle
System.out.println(parentHandle); //Prints the parent window handle
String anchorURL = anchor.getAttribute("href"); //Assuming u are clicking on a link which opens a new browser window
anchor.click(); //Clicking on this window
for (String winHandle : driver.getWindowHandles()) { //Gets the new window handle
System.out.println(winHandle);
driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
//Now your driver works on the current new handle
//Do some work here.....
//Time to go back to parent window
driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
Hope this helps!
Switching between browser window is different from switching b/w tabs.
In some browser windowhandler command may work but it wont work in all browser.
Here is the solution to navigate b/w tabs
for navigating left to right side:
Actions action= new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys(Keys.TAB).build().perform();
For navigating right to left :
Actions action= new Actions(driver);
action.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).sendKeys(Keys.TAB).build().perform();
In my case, the following code is working fine-
String oldTab=driver.getWindowHandle();
driver.findElement(pageObj.getL_Popup_Window()).click();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
driver.switchTo().window(newTab.get(0));
WebElement ele = driver.findElement(pageObj.getI_input_name());
ele.click();
ele.sendKeys(name);
driver.findElement(pageObj.getI_submit()).click();
driver.switchTo().window(oldTab);

How can i select text from browser screen with help of mouse events in selenium?

I am trying to select text which is already present on the browser.
I want to select that particular text and perform right click operation on it.
However, the page on the browser has disabled right click.
How can I select text in such situation?
Using a normal web browser without Selenium the only workaround that I can think about is to disable javascript to stop the script that prevents you from right clicking. So it should also work with a browser controlled by Selenium Webdriver.
I don't know if it will be OK for you because your website may be relying on javascript for essential features.
However if you don't need Javascript for your Selenium test you can try the following when you launch your driver :
FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);
I assume that you already know how to perform a right click because your question was only about dealing with the problem preventing you from doing this right click. But if not, you can also refer to this answer :
Select an Option from the Right-Click Menu in Selenium Webdriver - Java
Edit:
I'm sorry I really thought you could use Selenium actions to select the text you want but after some tests I didn't manage to perform a click and drag to select a text. The only thing that works for me in Chrome or Firefox is the following. It looks for a <p>which contains some text and then perform a double click to select a word.
driver.get("http://en.wikipedia.org/wiki/Java_(programming_language)");
WebElement text = driver.findElement(By.xpath("//p[contains(text(),'Java is')]"));
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();
However it only highlighs one word in the html element that contains your text, so it's not really convenient.
I've also tried to do Ctrl+F and type the text so that the web browser automatically select it but the browser doesn't do anything when executing :
Actions search = new Actions(driver);
search .sendKeys(Keys.chord(Keys.CONTROL,"+f")).sendKeys("Java is").build().perform();
It seems that Selenium can only send keys events to the html elements and not to the browser (in the case of ctrl+F).
I don't really see a solution for now, let's see if someone else can find a workaround. It's an interesting issue, it would also be useful for me to select a text the way you described
Move to middle of the element
Actions builder = new Actions(webDriverObject);
builder.moveToElement(element).build().perform();
Move to starting of element, click and hold, move to end
Integer width = element.getSize().getWidth();
Actions newBuilder = new Actions(webDriverObject);
newBuilder.moveByOffset(width/2,0).clickAndHold.moveByOffset(width,0).release().build().perform();

Categories

Resources