I've written a selenium code with java testng for submitting a form. After clicking submit button the page navigates to thankyou page. But before loading thankyou am getting a Security Warning dialog box which has the options called 'Continue' and 'Cancel'. How to click Continue through selenium control. There is no way for getting xpath or id of the continue button.
Had same problem, this worked for firefox 13 and selenium 2.0
Use spy to get the window info.
For firefox 13 windows class is MozillaDialogClass
WindowName is Security Warning.
declare import
[DllImport("user32.dll")]
public static extern int FindWindow(string className, string windowName);
make method
public static void SetOkButton(string className, string windowName)
{
int handle = FindWindow(className, windowName);
if (handle > 0)
{
if (SetForegroundWindow(handle))
{
SendKeys.SendWait("{ENTER}");
}
}
}
call the method
SetOkButton("MozillaDialogClass", "Security Warning");
Remember to add a wait before it appears otherwise your code may executed before alert actually appears. Following piece of code is working for me
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
If that is a JS confirmation box on load of the page, then (as the docs say), you can't do much. Selenium 2 (WebDriver) can handle these dialogs in a much better way:
driver.switchTo().alert().accept();
If that is a Firefox confirmation, you can't do anything with Selenium.
I'd give java.awt.Robot a try.
There is no xpath or id of the 'Continue' button on the 'Security Warning' dialog as this dialog is not a browser dialog. This dialog was generated by Java.
Selenium only automates browsers. Hence, it is beyond the scope of Selenium to click on the 'Continue' button.
Thankfully there is a way to click on the 'Continue' button by taking the help of these jars: jna.jar and jna-platform.jar and java.awt.Robot class.
If you don't know when 'Security Warning' will appear, you can write code to wait until the 'Security Warning' appears. This code keeps checking for the current active window title. Once 'Security Warning' dialog appears, the currently active window will become 'Security Warning' dialog. The code then uses TAB key to navigate to 'Continue' button and presses ENTER key.
You can use the below method after doing the necessary imports:
public void acceptSecurityAlert() {
//Keep checking every 7 seconds for the 'Security Warning'
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(1000, TimeUnit.SECONDS).pollingEvery(7, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
//Wait until the 'Security Warning' appears
boolean isTrue = wait.until(new Function<WebDriver, Boolean>(){
//implement interface method
public Boolean apply(WebDriver driver) {
try {
char[] buffer = new char[1024 * 2];
HWND hwnd = User32.INSTANCE.GetForegroundWindow();
User32.INSTANCE.GetWindowText(hwnd, buffer, 1024);
//System.out.println("Active window title: " + Native.toString(buffer));
//Check for 'Security Warning' window
if(Native.toString(buffer).equalsIgnoreCase("Security Warning")){
//After 'Security Warning' window appears, use TAB key to go to 'Continue' button and press ENTER key.
//System.out.println("Pressing keys...");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER); robot.delay(200);
robot.keyRelease(KeyEvent.VK_ENTER); robot.delay(200);
return true;
}
return null;
}catch(Exception e) {
System.out.println("Exception!");
e.printStackTrace();
}
return null;
}
});
}
Related
I have this alert box with an textbox which cannot be inspected and in want to sendKeys to this textbot.
inspect absent
public void handleprompt() throws InterruptedException {
driver.get("http://www.tizag.com/javascriptT/javascriptprompt.php ");
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Thread.sleep(3000);
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("abcd");
}
There is no error but the text is not visible in text box or my code is incorrect
Hai Bro there is nothing wrong with your code i just simply copy pasted your code and executed it it works absolutely fine
public void handleprompt() throws InterruptedException {
driver.get("http://www.tizag.com/javascriptT/javascriptprompt.php ");
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Thread.sleep(3000);
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("abcd");
prompt.Accept();
}
After accepting the alert popup you are able to see the text you entered.
I removed the sleep (it's not a good practice) and instead added a wait for the Alert, sendKeys, and then accept. I noticed that I didn't see the text in the alert after sending but when the alert was accepted, it showed the "abcd" text.
public void handleprompt() throws InterruptedException {
String url = "http://www.tizag.com/javascriptT/javascriptprompt.php";
driver.get(url);
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Alert prompt = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("abcd");
prompt.accept();
}
I tested this code and it's working.
I have automation scenario that sometimes the system return javascript alert and sometimes not at all. I don't know what the cause of this, probably the network issue. I already create the alert handler for this:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
I call this in one of my step that sometimes appear alert:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class);
Can you help me provide a better code from this?
Thanks a lot.
JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
Hope it will help you :)
You can modify the method isAlertPresent as given below and try it. It may help you.
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
You can include that particular exception in try catch. Then the exception will be catched and will not through any error and your execution will continue.
Also create a implicit wait to handle this with less timestamp.
#Then ("^I hover on (.+) menu and (.+) submenu$")
public void mousehover(String elementName,String subMenu) throws InterruptedException{
Actions actions = new Actions(webdriver);
WebElement menuHoverLink = webdriver.findElement(By.xpath("//a[text() = '" + elementName + "']"));
actions.moveToElement(menuHoverLink).build().perform();
Thread.sleep(2000);
actions.moveToElement(menuHoverLink).moveToElement(webdriver.findElement(By.xpath("//a[text() = '" + subMenu + "']"))).click().build().perform();
System.out.println("Sub menu "+subMenu+" Has been clicked");
}
Blockquote Hi every one. This is my code to done mouse hover event and then click sub link. But most of the time sub link click event is working. But some time which is not works. The mouse hover event has been done. But sub link click event is not triggering. Really don't know why this happen. Thanks in advance..
I would try somethin like moving to where you want to click and then just clicking. With hover menus you can get some odd behaviour from selenium about when an elemenet is and isnt clickable. Try;
actions.MoveToElement(menuHoverLink).Perform();
//wait til clickable, you are sleeping, a wait til element is both displayed and enabled would be better - can explain more if needed
action.Click().Perform();
note: I think just using peform will build the action without explicitly stating
EDIT:
I would assume that sometimes it takes longer than the 2seconds sleep time for the the element to be clickable. What exception is thrown?
Instead of thread.sleep use a wait to decide if the element can be clicked, something like:
public void WaitForElementToBeClickable(IWebElement element)
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
wait.Until<bool>((d) =>
{
if (IsElementDisplayed(element) && IsElementEnabled(element))
return true;
else return false;
});
}
public Boolean IsElementEnabled(IWebElement element)
{
try
{
return (element.Enabled);
}
catch (NoSuchElementException)
{
return false;
}
}
public Boolean IsElementDisplayed(IWebElement element)
{
try
{
return (element.Displayed);
}
catch (NoSuchElementException)
{
return false;
}
}
I am not sure whether selenium webdriver can handle Javascript alert/pop-up window.
I have a scenario like
1. User uploads a xls file and click on upload button
2. Alert/Pop-up window will be displayed . Click "OK" on window
Am able to automate the above scenario but the Alert/pop-up window is displayed while running the scripts.
Is their anyway workaround that we can handle javascript alert/pop-up window?
You can also try waiting for the alert to appear and then accepting it.
Below is the code for that (after the upload button is clicked):
try{
//Wait 10 seconds till alert is present
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//Accepting alert.
alert.accept();
System.out.println("Accepted the alert successfully.");
}catch(Throwable e){
System.err.println("Error came while waiting for the alert popup. "+e.getMessage());
}
Switch to default content
Dismiss alert after accepting "OK"
Otherwise your alert is from a different window which you'll have to switch to in order to dismiss
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
driver.switchTo().alert().defaultConent();
Mock it out. Call javascript behind the UI directly:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
}
There are the four methods that we would be using along with the Alert interface:
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
String getText() – The getText() method returns the text displayed on the alert box.
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
if(isAlertPresent(ldriver)){
Alert alert = ldriver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
Alert is a interface which have the abstract methods below
void accept();
void dismiss();
String getText();
void sendKeys(String keysToSend);
new WebDriverWait(driver,10).
until(ExpectedConditions.alertIsPresent()).accept();
alertIsPresent() internally return the
driver.switchTo.alert(); then we don't have to write it explicitly
hope this is been helpful
I use selenium Web Driver. I have opened a parent window. After I click on the link the new window opens. I choose some value from the list and this window automatically closes. Now I need to operate in my parent window. How can I do this? I tried the following code:
String HandleBefore = driver.getWindowHandle();
driver.findElement(By.xpath("...")).click();
for (String Handle : driver.getWindowHandles()) {
driver.switchTo().window(Handle);}
driver.findElement(By.linkText("...")).click();
driver.switchTo().window(HandleBefore);
This does not work though.
Try this before you click the link that opens the new window:
parent_h = browser.current_window
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back
public boolean switchBackParentWindowTitle(String windowTitle){
boolean executedActionStatus = false;
try {
Thread.sleep(1000);
WebDriver popup = null;
Set<String> handles = null;
handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
while (it.hasNext()){
String switchWin = it.next();
popup = driver.switchTo().window(switchWin);
System.out.println(popup.getTitle());
if(popup.getTitle().equalsIgnoreCase(windowTitle)){
log.info("Current switched window title is "+popup.getTitle());
log.info("Time taken to switch window is "+sw.elapsedTime());
executedActionStatus = true;
break;
}
else
log.info("WindowTitle does not found to switch over");
}
}
catch (Exception er) {
er.printStackTrace();
log.error("Ex: "+er);
}
return executedActionStatus;
}
This will not answer your question, however it might answer a similar one.
With SeleniumBase all you need to do is write:
self.switch_to_default_window()
And you're back to the parent window.