Handling print window in selenium webdriver - 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);

Related

File upload functionality of Selenium web driver for non-input button without AutoIt or Skuliii

I need to upload a document via Selenium WebDriver using Chromedriver. I have tried all the Action class and JavaScript stuff, but those do not work. I am assuming they do not work because those are relying on the button to be an input field, however, the upload button I'm dealing with is not. It's HTML looks like this:
Steps to reproduce:
Go to: https://www.fedex.com/apps/printonline/#!
Click on View Products under Marketing Material
Click on Get Started under Brochure
Click on Use your File to upload the file
Use Your File
I am able to click the use your file button, but I am not sure how I can upload the file.
driver.get("https://www.fedex.com/apps/printonline/#!");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Thread.sleep(6000);
if (driver.findElement(By.xpath("//area[#alt='close']")) != null) {
driver.findElement(By.xpath("//area[#alt='close']")).click();
}
driver.findElement(By.xpath("//a[#title='Marketing Materials']/child::button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//a[#title='Get Started - Brochures']")).click();
Thread.sleep(1000);
WebElement element = driver.findElement(By.xpath("//*[#class='btn fxg-btn-orange mycomputer-upload-link']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click()", element);
Ok so first of all get rid of those Thread.sleep(), use fluent wait with polling time, preferably as a function to locate the elements:
private WebElement waitFor(By locator) {
int timeout = 10;
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(200))
.withTimeout(Duration.ofSeconds(timeout))
.ignoring(NoSuchElementException.class);
return wait.until((driver) -> driver.findElement(locator));
}
Then you can click the buttons and upload the file like this:
waitFor(By.cssSelector("button.view-products")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("input.file-upload")).sendKeys("path_to_my_file");
Notice I am using the input element to upload the file - I am not clicking the a link, as you do not need to do that. Just send the path directly to the input element.

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

How can I check a checkbox on the popup window? 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();

How to Test Print-preview of Chrome browser using Chrome webdriver?

I have tried using switching between windows using
String winHandleBefore = driver.getWindowHandle();
<code to print>
for (String winHandle : driver.getWindowHandles())
driver.switchTo().window(winHandle);
driver.findElement(By.className("cancel")).click();
driver.switchTo().window(winHandleBefore);
This hangs my test case execution after it opens the print preview page.
Also tried with javascript executor method, but no use.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.close()", "");
Please suggest if it's possible to do so.
I have found the answer to my question. I used below code snippet.
//Create a Region for Desktop Screen
ScreenRegion s = new DesktopScreenRegion();
//Find target with below Image in Desktop Screen
Target target = new ImageTarget(new File("Image.png"));
ScreenRegion r = s.find(target);
// Create a mouse object
Mouse mouse = new DesktopMouse();
// Use the mouse object to click on the center of the target region
mouse.click(r.getCenter());
With the help of this snippet you would able to find the print or cancel and do the mouse click event and proceed with selenium tests. This was possible using sikuli API

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