selenium webdriver handle windows pop [duplicate] - java

This question already has answers here:
Alert handling in Selenium WebDriver (selenium 2) with Java
(5 answers)
Closed 6 years ago.
I am saving image from to my local system with selenium-webdriver (using Robot class):-
First time it save perfectly.
When I run my script second time again then it tries to save same image with the same name but windows pop appear The image with this name already exists. Do wish to save again with Ok and Cancel button. How to handle this Ok button.

You can handle Windows pop-up using a 3rd party tool Auto-IT integrated with eclipse. This will consist of an script editor (where you have to write a piece of code and save as ".au3") and inspector (used to inspect the properties of the window pup-up buttons).
Refer to - https://www.autoitscript.com/site/autoit/

you could also try to just send an enter press which would press whichever button is marked by default
if its more of an overlay then a real popup (like jquery or jsf in java) then you can select the buttons using xpath

Using selenium you can accept an Alert, try the following, I know this works in C#
IAlert alert = null;
try
{
alert = BrowserProcess.SwitchTo().Alert();
}
catch (Exception e)
{
//no alerts present, everything is ok
}
if (alert != null)
{
alert.Accept();
}
In java it would be something like this:
Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();

Related

selenium chrome driver select certificate popup confirmation not working

I am automating tests using selenium chromewebdriver 3.7. Whenever I lauch the site, I get a certificate selection popup like the one below
However I am not able to click on the OK button. These are the options I have tried
//I have tried getWindowHandle like this
String handle= driver.getWindowHandle();
this.driver.switchTo().window(handle);
//I have alos tried switching and accept
driver.switchTo().alert().accept();
//I have also tried to force the enter key like this
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// I also tried this way
Scanner keyboard = new Scanner(System.in);
keyboard.nextLine();
All my trials have failed. How can I click on OK on this popup window?
This is the closest solution I found which is not working Link here
I also had problems with accepting the warning for using a signed certificate. The solution of #eskoba worked like a charm. The functions are NOT final, because I let the enter button press for 10 times. I made this, because the webdriver needs a long time until it actually calls the url. In the meantime he starts pressing already.
In Python:
def threaded_function():
#Calls the website
browser.get(url)
def threaded_function2():
#Presses 10 times
for i in range(0,10):
pyautogui.press('enter')
#Calling the website and pressing 10 times in the same time
thread2 = Thread(target = threaded_function2)
thread2.start()
thread = Thread(target = threaded_function)
thread.start()
If still actual, I had same issue on Mac, and solution was simple:
for chrome is set AutoSelectCertificateForUrls policy like that:
defaults write com.google.Chrome AutoSelectCertificateForUrls -array-add -string '{"pattern":"[*.]example.com","filter":{"ISSUER":{"CN":"**cert issuer**"}, "SUBJECT":{"CN": "**cert name**"}}}'
for safari:
security set-identity-preference -c "**cert name**" -s "**example.com**"
then use it in code like
subprocess.call() in python
I had the same problem and I was able to solve it by using the robot, creating function for the url and passing it to a different thread.
Runnable mlauncher = () -> {
try {
driver.get(url);
} catch (Exception e) {
e.printStackTrace();
}
};
public void myfunction {
try {
Thread mthread = new Thread(mlauncher);
mthread.start
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
e.printStackTrace();
}
One suggestion would be, use Sikuli to click on OK button in the certificate.
Steps:
Take screenshot of OK button and save it.
Download sikuli-script.jar and add it to Project's Build path.
Take a screenshot of the UI Element to be clicked and save it locally.
Add the following code to the test case.
Screen s=new Screen();
s.click(“image name”);
Other functions Sikuli provides can be found here.
You can also skip being prompted when a certificate is missing, invalid, or self-signed.
You would need to set acceptInsecureCerts in DesiredCapabilities and pass that when you create a driver instance.
for example, in Python:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.CHROME.copy()
caps['acceptInsecureCerts'] = True
driver = webdriver.Chrome(desired_capabilities=caps)

Selenium Webdriver : Dismiss Chrome Alert

I want to select the check box Prevent this page from creating additional dialogs before selecting ok to close the alert
Currently i am using
Alert alert=driver.switchTo().alert();
//check the checkbox
alert.accept();
As an normal interactive user to check the check box i have to use a combination of <Tab> + <Space/Enter> keys. The <Tab> shifts the focus to the check-box and the <Space/Enter> checks the check-box.
Solutions Tried
I tried using Java sendKeys mechanisms ( Robot class, driver.sendKeys(), etc.), but an UnhandledAlertException is getting thrown.
I tried using alert.sendKeys which is different from driver.sendKeys() but it too failed
//check the checkbox
alert.sendKeys("\t");
alert.sendKeys("{TAB}");
alert.sendKeys("\uE004");
alert.sendKeys("\\U+0009");
alert.sendKeys(Integer.toString(KeyEvent.VK_TAB));
I am trying to avoid robot class as much as possible as i need to run the test in grid in which case robot class will not work.Any pointers on how to send keys to the alert window ?
Temporarily i could do it using a javascript window.alert = function() {}; by simply overriding the alert with an empty function just curious to know if it could be done with webdriver functions like alert.sendkeys or any other methods ??
Any help is greatly appreciated!!

WebDriver - how to get a page already open without modification

I need to enter a protected website.
Security requires a username and password, but with graphical components of Windows (no web code, like upload a file for example).
To skip this step, I coded a small Awt.Robot, which find and valid the 'pop-up' windows.
So I am with a web page open in the expected state.
How can I regain control, from this state, with WebDriver?
some kind of :
​​driver FirefoxDriver = new FireFoxDriver();
driver.get (page already open without modification and authentification);
Ideas?
To answer your question, it's not possible to take control of the already existing browser instance.
Some discussions:
How to use a already opened firefox for testing in Selenium
Getting around the JS popups is not easy and straightforward, using Robot solution is flaky. It will not work on Remote browsers etc.
Send username and password through url like http://username:password#your-app.com. Did you try something like below?
String url = "http://username:password#your-app.com";
driver.get(url);
Thanks to you, nilesh, I had an idea. I write for anyone who might encounter the same difficulty. My solution is made ​​very simple, I instantiate my driver and just before the get(url), I run my AWT.Robot is now a Thread. This allows me to not be bothered by the blocking property of driver.get(url);
private boolean openBrowserOnPage() {
try {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// run the robot which extends Thread
RobotHabile robot = new RobotHabile();
robot.start();
// Open the browser
driver.get(url);
// Wait for robot action
while(robot.isAlive()){
// not much, wait
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erreur : Impossible de se connecter/acceder au service '" + url + "'");
}
return false;
}
Hoping to help someone
For Purus, I will try again.
If I use WebDriver.driver.get(http://localhost/repository); the green popup appears, and that's all. The method will never finish. (1). This evil popup isn't a web component (not div, span, link, etc..) it's just a OS component (here Windows). It's impossible to manipulate this one with WebDriver.
So, just before WebDriver.driver.get(http://localhost/repository); I use a new class RobotHabile which extends Thread and use AWT.Robot.
The AWT.Robot can use keyboard, so when the evil popup appears(green), the Thread 1 is waiting for validation of the popup and with my RobotHabile robot = new RobotHabile();
robot.start();
With Thread 2 I can press my id, press tab for swith to password, press my pwd, and to finish press enter (2) .The robot does not target id and pwd fields. But as the popup already has focus, I can only fill with any character and tab key and enter. At this moment the evil popup is validate and the Thread 1 can normally continue.
better for your understanding ?

Selenium Webdriver screenshots do not show driver errors

I'm creating screenshots in my testcases with selenium webdriver, and while these indeed show what is visible in my web application, it doesn't show popups created by the browser.
I have found that in IE in some cases, my app triggers a JS debug popup in IE. This is of course an error and breaks the rest of my test, but the screenshot does not show the error. I presume this is because it's an IE native popup, rather than one trigger by my application.
Is it possible to get this included in the screenshots? I was thinking of maybe creating the screenshot with Robot#createScreenCapture() but obviously that wouldn't show anything useful if the browser is minimized.
So, a few possible solutions:
- can you detect if an error message pops up in a browser
- is it possible to maximise/focus the browser while running?
- can you take screenshots from selenium with the popups showing?
Selenium will take a screenshot that represents the rendered DOM that the browser shows the end user by intercepting the rendered image that the browser is displaying and taking a copy of it.
It does not take a desktop screenshot so the screenshots shown will not show anything covering the browser window. JavaScript alerts are not part of the rendered DOM so you will not see these in Selenium screenshots.
Maybe because the driver is not with the Alert/Window active?
You could try something like this:
private void CheckForOtherWindows()
{
//Check for any other window open
if (driver.WindowHandles.Count > 0)
{
foreach (string window in driver.WindowHandles)
{
driver.SwitchTo().Window(window);
TakeScreenshot();
}
}
//Check for alert window
try
{
driver.SwitchTo().Alert();
TakeScreenshot();
}
catch
{
//Nothing
}
}
This is not tested, not sure if works. Just giving the idea. :)
Edit:
To maximize the window is easy:
driver.Manage().Window.Maximize();
Hope it helps.
You can use this as below:
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), new File("E:\\ScreenShot\\screenshot.png"));

Switching between user name and password text box and entering corresponding values using Selenium WebDriver java

I am using selenium to navigate to a page and take screenshots using Internet Explorer. But the problem is the login is taken care by a Javascript alert box. Now Selenium has a facility where the focus can be brought to the alert box by using Alert element and I have managed to bring the focus and also enter some values in the user name text box.
The problem is Selenium does not switch focus to the password text box and enters the username and password in the same box. I tried Java AWT Robot to click on the tab key and it changes the focus, but Selenium does not recognized this and it continues entering the user name and password in the same box.
Below is my code:
Robot robot = new Robot();
driver.get("the url");
Alert alert = driver.switchTo().alert();
alert.sendKeys("username");
robot.keyPress(KeyEvent.VK_TAB);
alert.sendKeys("password");
alert.accept();
What am I missing here? Is my approach here correct or do I have to take a different route?
hi Madusudanan Try the code by commenting the another switch method.
Robot robot = new Robot();
Alert alert=dr.switchTo().alert();
dr.get("the url");
alert.sendKeys("username");
//dr.switchTo().alert();
robot.keyPress(KeyEvent.VK_TAB);
alert.sendKeys("password");
alert.accept();
Not a Java answer but since I found this question searching for a .net answer to this problem.
If you're using .NET you'll need to use SendKeys rather than Robot
using System.Windows.Forms;
_driver.SwitchTo().Alert().SendKeys("Username");
SendKeys.SendWait("{TAB}");
SendKeys.SendWait("password");
SendKeys.SendWait("{Enter}");
Hope this helps someone!
According to your question, after focusing on Password field Selenium WebDriver failed to enter/input/type it's corresponding value. You can do type the password value by using Robot class. The following is the whole code:
//First write a method to use StringSelection
public void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
Robot robot = new Robot();
driver.get("Your URL");
Alert alert = driver.switchTo().alert();
alert.sendKeys("username");
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
//call setClipboardData method declared above
setClipboardData("Your Password");
//Copy Paste by using Robot class
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
alert.accept();
I create code like that from any source and work after add: a.keyRelease(KeyEvent.VK_ADD);
// Initialize InternetExplorerDriver Instance.
WebDriver driver = new InternetExplorerDriver();
// Load sample calc test URL.
driver.get("your homepage testing");
//Code to handle Basic Browser Authentication in Selenium.
Alert aa = driver.switchTo().alert();
Robot a = new Robot();
aa.sendKeys("beyond"+"\\"+"DND");
a.keyPress(KeyEvent.VK_TAB);
a.keyRelease(KeyEvent.VK_TAB);
a.keyRelease(KeyEvent.VK_ADD);
setClipboardData("P#ssw0rd");
a.keyPress(KeyEvent.VK_CONTROL);
a.keyPress(KeyEvent.VK_V);
a.keyRelease(KeyEvent.VK_V);
a.keyRelease(KeyEvent.VK_CONTROL);
aa.accept(); private static void setClipboardData(String string)StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Using java.awt.Robot class comes with two main drawbacks.
Mac issue:
On a Mac OS, when we instantiate a Robot class, Java app launches in the background and takes away the focus (so some in the community were sending VK_META (Cmd key) and VK_TAB to get back to the alert). Since copy & paste shortcut keys are different for Mac, that needs to be also handled (using VK_META in place of VK_CONTROL).
Jenkins or remote runner issue:
Even if we accommodated the issue above, eventually when tests are run from Jenkins job, Robot instantiation becomes a problem again (Robotframework selenium execution through jenkins not working)
Fortunately, sendKeys can handle the tab key (as a scan code) and the code below worked for me.
Alert alert = driver.switchTo().alert();
alert.sendKeys("username" + Keys.TAB.toString() + "password");
alert.accept();

Categories