How can I check a checkbox on the popup window? Selenium Webdriver - selenium-webdriver

When a popup window open how can I handle on this window?
driver.switchTo().defaultContent();
MenuUtil.doClickMenu(selenium, driver, "Access 2G", "Cảnh báo", "Giám sát cảnh báo BTS");
ControlBase.waitForLoadOk(5);
CheckBoxUtil.doCheckByXpath(selenium, "//*[#id='listRow1']/tbody/tr[1]/td[18]/input");
ControlBase.waitForLoadOk(5);
ButtonUtil.doClickByLabel(driver, "Cập nhật");
ControlBase.waitForLoadOk(5);
CheckBoxUtil.doCheckByXpath(selenium, "//*[#id='txtName']");

Generally I use the Selenium IDE. Here you can 'click & record', which allows you to then get the XPath of the JS pop-up alert box.
I would suggest you first check for the alert box showing up with something such as this:
if (selenium.isAlertPresent()){
System.out.println(selenium.getAlert()); //show alert text message
selenium.click("id=alertbox_ok_btn"); //click OK on alert box
}
Download Selenium IDE from here: http://docs.seleniumhq.org/download/
Also, refer to Selenium's documentation for Java here: http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html

Try the below code written in JAVA
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("Your application URL");
String parentWindow = driver.getWindowHandle();
//click on the link/box/whatever to open the pop up
driver.findElement(By.xpath("")).click();
Set <String> popupWindows = driver.getWindowHandles();
for(String popup : popupWindows){
driver.switchTo().window(popup);
//you can use getTitle/getCurrentUrl to match with title/url of the pop up
if(driver.getTitle().equals("actual title on the pop up")){
break;
}
}
//Write a code to check a checkbox
//Close the pop up
driver.close();
//Come back to the parent window
driver.switchTo().window(parentWindow);
//Code if you want to test/do something else
driver.close();

Related

Handling print window in selenium webdriver

There is a print button in my application. When I click on the button print windows open with cancel and print button.
I want to click on cancel button in the print window.
I know handling print window is not possible using selenium webdriver alone. I tried using Robot class. But it is not working.
WebDriver driver = (WebDriver) new ChromeDriver();
driver.get("https://www.joecolantonio.com/SeleniumTestPage.html");
driver.manage().window().maximize();
Thread.sleep(2000);
//clicking on the print button
driver.findElement(By.id("printButton")).click();
//print window opens
//creating robot class object
Robot r = new Robot();
r.delay(1000);
r.keyPress(KeyEvent.VK_ESCAPE);
r.keyRelease(KeyEvent.VK_ESCAPE);
The print window opens but nothing happens after that. I was expecting escape button will make the window exit but its does not happens. But manually when I press escape button print window disappears.
Actually you can handle print page window using javascript executor in selenium.
following codes are c#.
If your program is stuck after opening window.print(); which in my case it was happening, try to use the following javascript code instead:
setTimeout(function() { window.print(); }, 0);
this will release your application and you can work with the print page.
then you can switch to the print page simply by the following line:
driver.SwitchTo().Window(driver.WindowHandles.Last());
then you can get the JSPath of any element in print window and interact with it
(IWebElement)js.ExecuteScript($"return {JSPath}").Click();
A complete example of this, is as follows where print window will be opened then the cancel button will be clicked after 2 seconds.
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("setTimeout(function() { window.print(); }, 0);");
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(2000);
string JSPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.cancel-button')";
IWebElement cancelBtn = (IWebElement)js.ExecuteScript($"return {JSPath}");
cancelBtn.Click();
Since the elements in print window exist in the shadow root you cannot select them by selenium web driver that's why I used Javascript Executor to get the cancel button.
Use tab and then click escape.I think it works.
Using Robot is not something I would recommend to handling the print preview page as it will bite you back when you will be running your tests in Parallel mode.
You could click "Cancel" button as follows:
Switch to the Print Preview window using driver.switchTo() function:
driver.switchTo().window(driver.getWindowHandles().stream().filter(handle -> !handle.equals(driver.getWindowHandle())).findAny().get());
Find preview-app Shadow DOM element using i.e. XPath and convert it into a WebElement
WebElement printPreviewApp = driver.findElement(By.xpath("//print-preview-app"));
WebElement printPreviewAppContent = (WebElement) driver.executeScript("return arguments[0].shadowRoot", printPreviewApp);
Find preview-header Shadow DOM element using i.e. CSS and convert into a Selenium's Web Element
WebElement printPreviewHeader = printPreviewAppContent.findElement(By.cssSelector("print-preview-header"));
WebElement printPreviewHeaderContent = (WebElement) driver.executeScript("return arguments[0].shadowRoot", printPreviewHeader);
Locate Cancel button and click it
printPreviewHeaderContent.findElement(By.cssSelector("paper-button[class*=cancel]")).click();
Answer for someone else who still looking solution
To download save as a pdf from the print pop-up window from any web
Add argument
options.addArguments("kiosk-printing");
This will prevent to open any popups from clicking on any print button.But a window dialog folder will open to download the file as a pdf.
Now you need to input the file name and press enter button. For this, we will use the robot class
StringSelection s=new StringSelection("remotePetrol_report.pdf"); // Set the File Name
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s,null);
//native keystrokes for CTRL, V, and ENTER keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Unable to automate the Popup in selenium

i am unable to identify the web elements when a pop up is displayed on clicking "select your family members" in the below website, i am not sure how to automate this ?
I have tried using Switch window and alert windows.
http://health.policybazaar.com/?utm_content=home_v3
There is no need to switch any window , Use following code
driver.get("http://health.policybazaar.com/?utm_content=home_v3");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.id("input_6")).click();
Updated :
WebDriverWait wait =new WebDriverWait(driver, 120);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='prequote-member-left-section']/md-checkbox[#name='checkboxSelf']/div[1]")));
driver.findElement(By.xpath("//div[#class='prequote-member-left-section']/md-checkbox[#name='checkboxSelf']/div[1]")).click();
Note : Use ExplicitWait to make element visible on next popup and then click

Code is not getting executable after opening pop up in selenium

Please find below the code :
d.findElement(By.id("txtUserName")).clear();
d.findElement(By.id("txtUserName")).sendKeys("polarissupport#polaristest.net");
Thread.sleep(2000);
d.findElement(By.name("txtTempBox")).clear();
Thread.sleep(2000);
d.findElement(By.id("txtPassword")).sendKeys("password");
d.findElement(By.id("btnsubmit")).click();
Thread.sleep(2000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_rdoAdmin")).click();
Thread.sleep(2000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_lnkContinue")).click();
Thread.sleep(5000);
//GC Inbox
String s1 = "CHR-665";//d.findElement(By.id("ctl00_ContentPlaceHolder1_lblrequestidtext")).getText(); //For taking Request Id
String tem[] = s1.split("-");
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_txtGrantID")).sendKeys(tem[1]);
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_lnkSearch")).click();
Thread.sleep(5000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_grdAdminGrantCHR_ctl00_ctl04_btnAction")).click();
Thread.sleep(8000);
d.findElement(By.xpath("//*[#id='ctl00_ContentPlaceHolder1_lnkReleasePayment']")).click();
After the last line which opens the Pop-up, code is not getting executable to handle this opened Pop-up.
Please find below the code through which I handled the Pop-up:
String MainWindow=d.getWindowHandle();
Set<String> set=d.getWindowHandles();
Iterator<String> it=set.iterator();
while(it.hasNext())
{
System.out.println("Inside While");
String ChildWindow=it.next();
if(!MainWindow.equalsIgnoreCase(ChildWindow))
{
d.switchTo().window(ChildWindow);
d.close();
}
}
System.out.println("Outside While");
d.switchTo().window(MainWindow);
Please let me know how to execute Pop-up handling code when Pop-up is opened because when I close the Pop-up manually then only this Pop-up handling code executes not at the time when Pop-up is opened.
Please let me know if question doesn't provide satisfactory information.
Thanks
Try Using Alert class or PopupWindowFinder Code in the link is based on c#, i hope you can convert it to your desired language easily
popup's in selenium webdrivers

File Upload button is not working using Selenium webdriver

Am trying to upload a jpeg image to my application . But on webpage we can upload other jpeg images as well in their respective section. Here as per the HTML, Upload button have the same attributes defined for other upload sections.
However ,When I inspect the xpath for Unique element for Upload button , I found the below xpath=//table/tbody/tr[1]/td[1]/div/div/div/input[#class='bttnUpload'] and verified using xpath checker
Below is Webdriver code used
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//Test URL
driver.get("URL");
// UN & PWD
driver.findElement(By.xpath("//input[#id='UserName']")).clear();
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys("UN");
driver.findElement(By.xpath("//input[#id='Password']")).clear();
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys("pwd");
driver.findElement(By.xpath("//input[#id='btnSubmit']")).click();
//Validate the User logged in
if(driver.getPageSource().contains("UN Kumar"))
System.out.println("UN is logged in");
else
System.err.println("UN not logged in");
//Click on Asset Menu and LookUp Assets sub menu
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//a[#href='http://ccqweb1.cloudapp.net//Main.aspx? MenuId=15']"))).build().perform();
driver.findElement(By.linkText("Lookup Assets")).click();
//Search for Loan Number
driver.findElement(By.xpath("//input[#id='ctl10_txtLoannumber']")).sendKeys("787878717");
driver.findElement(By.xpath("//input[#id='ctl10_cmdSearch']")).click();
Thread.sleep(2000);
// Get the window handle before clicking on link
String winHandleBefore = driver.getWindowHandle();
//Click on Initial Occupancy task
driver.findElement(By.xpath("//a[#id='ctl09_gvPendingTasks_ctl02_lnkTask']")).click();
Thread.sleep(2000);
// Switch to New Window
String child = driver.getWindowHandle();
for(String parent : driver.getWindowHandles()){
driver.switchTo().window(parent);
}
/**Exterior Photos tab **/
//Click on Exterior tab
driver.findElement(By.xpath("//a[#id='ctl09_btnExteriorPhotos']")).click();
//Front View* `enter code here`
//Click on Manual Upload button
driver.findElement(By.xpath("//div/input[#onclick='DisplayManualUpload(event)']")).click();
WebElement FileUpload_FrontView= driver.findElement(By.xpath("//input[#class='fleManuleUpload']"));
FileUpload_FrontView.sendKeys("\\Front_view.jpeg");
Thread.sleep(500);
driver.findElement(By.xpath("//table/tbody/tr[1]/td[1]/div/div/div/input[#class='bttnUpload']")).click();
The Upload image is getting selected but Upload button not is clicked so am not able to upload the file.
Can you help me to solve this ?
I'm pretty sure it's just a typo.
As well as for the upload locator
(//input[#class='fleManuleUpload'] ->e.g. fleManualUpload )
as for the upload button
([#class='bttnUpload'] -> btnUpload ).
In General: Why don't you use more consistent css locators or just ids?
By.xpath("//input[#id='UserName']"
use easily:
By.id("UserName")
To give you a better answer please upload the error message when you run this.
The reason behind this is:
FileUpload_FrontView.sendKeys("C:\\Users\\prabhakar.y\\Desktop\\Pics for Uploading\\Front_view.jpeg");
You are having space in foldername - "Pics for Uploading".
Try out by giving
File f = new File("Pics for Uploading\\Front_view.jpeg");
FileUpload_FrontView.sendKeys(f.getAbsolutePath());
and this folder should be inside your current workspace (Its a good practice). Or else remove space from foldername.

Selenium webdriver: Unable to send keys In a new popup window

Using selenium web-driver I am trying to put region name In the text box In new popup screen and click on save button. I using the below script for that
String mainWindowHandle1=driver.getWindowHandle();
driver.switchTo().window(mainWindowHandle1 );
driver.findElement(By.id("MainContent_imgAddRegion")).click();
Thread.sleep(5000);
java.util.Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite1 = s1.iterator();
while(ite1.hasNext())
{
String popupHandle=ite1.next().toString();
if(!popupHandle.contains(mainWindowHandle1))
{
driver.switchTo().window(popupHandle).findElement(By.id("txtRegionName")).sendKeys("South Region");
Thread.sleep(3000);
driver.findElement(By.id("txtRegionName")).sendKeys("South Region");
Thread.sleep(1000);
driver.findElement(By.id("btnSave")).click();
By doing this I am able to open the new popup screen to enter the region but, I am unable to send keys [region name] and save the text.Even I am not getting any failed report when I run the test.
This may be due to iFrames presence.
Look in the HTML code and check if the text field that you are trying to send keys to and the save button are included in some sort of iFrame.
If so, you will need to do something like:
driver.switchTo().defaultContent();
driver.switchTo().frame("framename");
driver.findElement(By.id("txtRegionName")).sendKeys("South Region");
driver.findElement(By.id("btnSave")).click();
Hope it helps!

Resources