Handling multiple windows in IE and Chrome browsers - selenium-webdriver

In the below code,
//Element clicked in parent window
driver.findElement(By.id("ID")).click();
//Once after clicking the ID, system takes the user to a different tab in chrome and launches an external link
//In IE the same external link will launch in a new browser which is different from chrome behavior
Iterator<String> browsers = driver.getWindowHandles().iterator();
while(browsers.hasNext()){
driver.switchTo().window(browsers.next());
//Element to be clickable in the child window or external site
driver.findElement(By.xpath(".//button")).click();
Can anyone help me out how can we handle the scenario,i want something which works both in IE and chrome. Currently the above code works in chrome but not in IE as the external link opens in a new browser. I am not able to handle the scenario

Try the below method for IE:
Java:
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
cap.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING,true);
cap.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,"accept");
cap.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS,true);
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,"");
WebDriver dr = new InternetExplorerDriver(cap);
C#:
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.EnsureCleanSession = true;
options.IgnoreZoomLevel = true;
options.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
options.RequireWindowFocus = true;
options.InitialBrowserUrl = "";
string iedriver = TestContext.DataRow["IEDRIVER"].ToString();
dr = new InternetExplorerDriver(iedriver,options);

Related

Automating windows SaveAs dialog using FlaUI

I am at my wits end, trying to automate our tests for the Windows SaveAs-dialog.
The thing is that the automation code works on some machines but not all.
It works on my local box and a few other, but we need to make it work on all our test machines. Something is different but what I can see sofar is
Same windows version
Same dotnet --info
The test code I have tried to make work is something like
...
var app = FlaUI.Core.Application.Launch("FlaUISaveDialog.exe");
using (var automation = new UIA3Automation())
{
var window = app.GetMainWindow(automation);
var button1 = window.FindFirstDescendant(cf => cf.ByAutomationId("ClickIt"))?.AsButton();
button1?.Patterns.Invoke.PatternOrDefault.Invoke();
Thread.Sleep(2400); // Wait for window to appear!
var dialog = window.FindFirstDescendant(cf => cf.ByControlType(ControlType.Window));
Thread.Sleep(1000);
var fileNameTextBox = dialog.FindFirstDescendant(e => e.ByAutomationId("1001"));
fileNameTextBox.Focus();
fileNameTextBox.Patterns.Value.Pattern.SetValue(resultFile);
Thread.Sleep(2400);
//FlaUI.Core.Input.Keyboard.Press(VirtualKeyShort.RETURN);
var save = dialog.FindFirstChild(e => e.ByAutomationId("1").And(e.ByControlType(ControlType.Button)));
save.Focus();
var mousePoint = new Point(save.BoundingRectangle.X + save.BoundingRectangle.Width/2, save.BoundingRectangle.Y + save.BoundingRectangle.Height/2);
FlaUI.Core.Input.Keyboard.Press(VirtualKeyShort.RETURN);
//FlaUI.Core.Input.Mouse.Click(mousePoint);
//save.Patterns.Invoke.Pattern.Invoke();
Thread.Sleep(2400); // Wait for file save to complete
Assert.IsTrue(File.Exists(resultFile));
}
After another day going at this, I found that it seems to be the "SetValue" pattern that looks like it works, but doesn't change the Dialogs actual filename.
But moving the mouse,clicking and typing like below actually works:
var fileNameTextBox = dialog.FindFirstDescendant(e => e.ByAutomationId("1001"));
var mousePoint = new Point(fileNameTextBox.BoundingRectangle.X + fileNameTextBox.BoundingRectangle.Width/2, fileNameTextBox.BoundingRectangle.Y + fileNameTextBox.BoundingRectangle.Height/2);
Thread.Sleep(1000);
FlaUI.Core.Input.Mouse.MoveTo(mousePoint);
FlaUI.Core.Input.Mouse.Click(mousePoint);
Thread.Sleep(1000);
FlaUI.Core.Input.Keyboard.TypeSimultaneously(VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_A);
Thread.Sleep(1000);
FlaUI.Core.Input.Keyboard.Type(resultFile);
Thread.Sleep(1000);
FlaUI.Core.Input.Keyboard.Press(VirtualKeyShort.RETURN);
Edit #2: I seems that it is the Windows Explorer option "View File name extensions" that affects the automation behavior of the "SaveFileDialog". If we turn on "View file name extensions" the "SetValue" pattern starts working. Turn the setting off and the "SetValue" stops working! Unexpected, to say the least!

Element is not clickable at point ... error when using headless browsing

I have this error "org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (209, 760)", when I run the piece of code below in headless mode. When it is run with browser displayed I have no error and test passes fine. As you can see below, I trie with waiting, js executor, actions move to element but still no good result. I am using xpath to locate / define the element, and not coordinates. Why is this happening please and how can I solve it? Thanks in advance.
#Test(priority = 1)
public void verifyAddUserWithMarkedMandatoryFields() {
// accessing add user webpage / functionality
userListObject.getAddUserButton().click();
// inserting data to complete form
addOrEditUserPageObject.insertCredentials(userModel.getUsername(), userModel.getEmail(), "", userModel.getPassword());
// clicking Submit when becoming enabled
WebDriverWait myWaitVariable = new WebDriverWait(driver, 5);
myWaitVariable.until(ExpectedConditions.elementToBeClickable(addOrEditUserPageObject.getSubmitButtonAddOrEdit()));
// Actions actions = new Actions(driver);
// actions.moveToElement(addOrEditUserPageObject.getSubmitButtonAddOrEdit()).click().perform();
JavascriptExecutor jse = (JavascriptExecutor)driver;
// jse.executeScript("scroll(209, 760)"); // if the element is on top.
jse.executeScript("scroll(760, 209)"); // if the element is on bottom.
addOrEditUserPageObject.getSubmitButtonAddOrEdit().click();
}
You should add screen size for the headless mode, something like this:
Map<String,String> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadsPath); // Bypass default download directory in Chrome
prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
ChromeOptions opts = new ChromeOptions();
opts.setExperimentalOption("prefs", prefs);
opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage");
driver = new ChromeDriver(opts);
I put much more things here, the only relevant point here is "--window-size=1920,1080", this should resolve your problem.
The rest is to show how things are managed, including other relevant settings for headless mode.

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

Open a new window (or new tab) programmatically instead of always a popup

I'm trying to create a new Window with AngularJS
var _url = 'http://extern.com/index.html';
$window.open(_url);
It always opens a pop-up window, but never a normal window or a new tab. Why?
I use Angular 1.2.9 with Chrome, Firefox and IE10.
My problem is only the chrome 34!
$window.open is really just the same as window.open, which doesn't have much to do with angular. In terms of opening in a new window or tab, that is up to the user, and the settings they have initialised with their browser.
Also the same goes for anchor links with target="_blank".
var _url = 'http://extern.com/index.html';
var tabWindowId = window.open('about:blank', '_blank');
tabWindowId.location.href = _url;
Try this
var _url = 'http://extern.com/index.html';
window.location.href = _url;

Could not switch between browsers in selenium webdriver

Iam trying to switch between browser ie on click of a button it launches a new browser it
is finding the handle ..the problem is it is not able to find the object inside the new browser searched with id,xpath,name etc can some one give me any suggestion on the same.
also it is able to match the url as well.
please provide me the solution on the same.
below is the code.
//Previous screen
Set windows = driver1.getWindowHandles();
driver1.findElement(By.id("findButton")).click();
//switching handle for the new screen
driver1.switchTo().window("Customer Search");
driver1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
int i = 1;
while(i<= 10){
for (String handle : driver1.getWindowHandles()) {
String myTitle = driver1.switchTo().window(handle).getTitle();
System.out.println("myTitle value : " +myTitle);
//customer search is the new window title
if(myTitle.equalsIgnoreCase("Customer Search")){
driver1.manage().window().maximize();
//if i pass the right url of the screen that is also matching here i have given dummy("sshsj")
if(driver1.getCurrentUrl().equalsIgnoreCase("sshsj"));
{
System.out.println("Url is matching");
//But not able the recognise the object on the new window.
driver1.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
}
You can use JS to open a new window, it's faster.
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open()");
Then to switch windows, use the window handles:
List<string> handles = driver.WindowHandles.ToList<string>();
driver.SwitchTo().Window(handles.Last());
driver.get(url);
driver.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
It is possible that the element may be present inside an iframe. In that case, you need to switch to that iframe before you can access any element inside the iframe.

Resources