Bring the Firefox Browser to Front using selenium Java (Mac OSX) - java

I am using three instances of fire fox driver for automation.I need to bring current active firefox browser into front, Because I am using some robo classes for some opertation. I had tried java script alert for google chrome in mac ( same operation) and its worked fine. In windows used user32 lib. In the case of firefox mac its showing the alert in background but the web page is not come into front.
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
The above code I used for chrome in Mac. Same code is working and showing alert for firefox but the window is not coming to front.
Please suggest if there any other method for doing the same in firefox.

Store the window handle first in a variable, and then use it to go back to the window later on.
//Store the current window handle
String currentWindowHandle = this.webDriver.getWindowHandle();
//run your javascript and alert code
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
//Switch back to to the window using the handle saved earlier
this.webDriver.switchTo().window(currentWindowHandle);
Additionally, you can try to maximise the window after switching to it, which should also activate it.
this.webDriver.manage().window().maximize();

Try switching using the window name:
driver.switchTo().window("windowName");
Alternatively, you can pass a "window handle" to the switchTo().window() method. Knowing this, it’s possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
Based on the Selenium documentation: http://docs.seleniumhq.org/docs/03_webdriver.jsp

As described in other topics, you can use
driver.manage().window().setPosition(new Point(-2000, 0));
too.

# notifications for selenium
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
current_path = os.getcwd() # current working path
chrome_path = os.path.join(current_path, 'chromedriver')
browser = webdriver.Chrome(executable_path=chrome_path, chrome_options=chrome_options)
browser.switch_to.window(browser.current_window_handle)
browser.implicitly_wait(30)
browser.maximize_window()
browser.get("http://facebook.com")

Only thing that worked for me on mac: self.driver.fullscreen_window().

Related

How to switch focus between windows using WinAppDriver Java

I am new to windows automation using win app driver.
Our application is developed with chromium browser and we are using win app diver to automate since the main app we are trying to open is windows based.
When I click on Ok button opens another window(Window B). I have 2 windows opened window 1 and window 2. I need to perform actions on both the windows for that I need to shift the focus between two windows. When I use getwindowhandles() method I am getting number of windows opened as 1.
How can I switch between windows using winapp driver.
Appreciate your help.
Thanks
I am using in my code:
this.driver.SwitchTo().Window(this.driver.WindowHandles[0]);
However, I do not expect this to work in your case, as your number of open windows is 1, than means that there is no second window to switch to.
So in your case you can use root session in order to attach to your window:
AppiumOptions rootSessionOptions = new AppiumOptions();
rootSessionOptions.AddAdditionalCapability("app", "Root");
rootSessionOptions.AddAdditionalCapability("deviceName", "WindowsPC");
_driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), rootSessionOptions);
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
var VSWindow = _driver.FindElementByName("Your project name without .csproj - Microsoft Visual Studio");
var VSTopLevelWindowHandle = VSWindow.GetAttribute("NativeWindowHandle");
VSTopLevelWindowHandle = (int.Parse(VSTopLevelWindowHandle)).ToString("x");
AppiumOptions VisualStudioSessionOptions = new AppiumOptions();
VisualStudioSessionOptions.AddAdditionalCapability("appTopLevelWindow", VSTopLevelWindowHandle);
_driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), VisualStudioSessionOptions);
_driver.SwitchTo().Window(_driver.WindowHandles[0]);
Reference:
https://github.com/microsoft/WinAppDriver/issues/978
OpenQA.Selenium.WebDriverException: [windowHandle] is not a top level window handle solution
This code works for me (windows automation using win app driver) with C#
//Switch to the next window in desktop application:
IList<string> toWindowHandles = new List<string>(_driver.WindowHandles);
Thread.Sleep(6000);
_driver.SwitchTo().Window(_driver.WindowHandles[0]);
With Java:
Thread.sleep(5000);
//Switch to the next window in desktop application:
Set<String> windowHandles = driver.getWindowHandles();
driver.switchTo().window(windowHandles.iterator().next());

Customize the browser icon when running a Selenium session?

I have some Selenium sessions where, if certain events occurs, I spawn a new browser and leave the old one as is so I later on can manually intervene. The problem is that it is hard to distinguish between such a deserted browser session and the one that is currently running.
Ideally I would like to add a badge to the browser icon that is displayed in the application switcher (cmd-tab) and the dock (but other solutions/suggestions are also welcome, like add something to the name of the browser). Is that possible?
Using Java on a Mac. A solution can be platform specific.
You can use below execute_script (This python code use java equalent)
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get(
"https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page")
head = driver.find_element_by_tag_name("head")
link = driver.find_element_by_css_selector('link[rel="shortcut icon"]')
driver.execute_script('''var link = document.createElement("link");
link.setAttribute("rel", "icon");
link.setAttribute("type", "image/png");
link.setAttribute("href", "https://i.stack.imgur.com/uOtHF.png?s=64&g=1");
arguments[1].remove();
arguments[0].appendChild(link);
''',head,link)
time.sleep(70000)
you can use link element on head tag to add favicon. THe above code is an exaple where stackoverflow site will showup with my avatar
Output:
You should find the current link the website uses, remove it and replace it with your new link as shown in the code

Maximize browser window in LeanFT

I am looking for some solution, like this in Selenium WebDriver:
ChromeOptions options = new ChromeOptions();options.addArgument("--start-maximized");
So browser window should be maximized when test is executed.
I found a profile based solution for this problem, but it opens a lot of tabs, which is maybe caused by escape characters.
#Test
public void chromeWithProfileLaunch() throws Exception {
String profileDir = "--user-data-dir=\"c:\\Temp\\profile1\""; //should be different folder every time
String leanftChromeExtension = "--load-extension=C:\\Program Files (x86)\\HPE\\LeanFT\\Installations\\Chrome\\Extension"; //to load the LeanFT extension
String homePage = "www.google.com"; //the homepage to start with
new ProcessBuilder("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", profileDir, leanftChromeExtension, homePage)
.start();
Thread.sleep(2000); //wait for Chrome process to load
Browser openedBrowser = BrowserFactory.attach(new BrowserDescription.Builder().title("Google").type(BrowserType.CHROME).build());
Verify.areEqual(homePage, openedBrowser.getURL());
}
I don't know about maximized but LeanFT supports putting the browser in fullScreen mode.
LeanFT doesn't support maximize() out of the box yet.
However, you could use sendKeys() method.
I'm not entirely sure if you can to it on the browser instance directly, or you need to getPage() first, but you can definitelly send Super key (win key) + ↑ as specified here. ↓ for restoring back to the initial state.
Here's an example using sendKeys with Java SDK if you need it.

Selenium not detecting the second window in IE

My application opens up a new window on clicking a button and i need to perform some actions in that window. But the response getWindowHandles() method of selenium webdriver has only one window id in it. This happens especially if there is a delay in calling the getWindowHandles() after opening the new window. There is a known issue with selenium.
https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration
But even the solution for that is not working for me.
Code is as follows
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
RemoteWebDriver driver = new
RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
driver.get("https://<url>");
WebElement userName = driver.findElement(By.name("usr_name"));
userName.sendKeys("ABCD");
WebElement password = driver.findElement(By.name("usr_password"));
password.sendKeys("password");
WebElement login = driver.findElement(By.name("OK"));
login.click();
WebElement popup= driver.findElement(By.name("popup"));
popup.click();
Thread.sleep(1000);
Set<String> windowHandles = driver.getWindowHandles();
System.out.println(windowHandles);
The Set "windowHandles" will return only one window :
"[fcdad457-9090-4dfd-8da1-acb9d6f73f74]"
But if i remove the sleep. it will return two window ids :
[90cc6006-0679-450c-a5b3-6602bcb41a16, 7211bbfd-2616-4460-97e7-56c0e632c3bb]
I cannot remove the sleep as this is just a sample program and in the real application there will be some delay in between. Please let me know your thoughts.This issue is only for IE11.
Blue screen - Home Page;
Grey Screen - Popup
There a couple of things which you have to take care while dealing with InternetExplorer as follows :
As you mentioned There is a known issue with selenium documented in GitHub, these are not issues as such but is the combined set of Required Configuration while dealing with InternetExplorer. Without taking care of these settings InternetExplorer may not behave as per expectation. The following items are critical to demonstrate proper behavior of InternetExplorer v11 :
Enhanced Protected Mode must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog.
The browser Zoom Level must be set to 100% so that the native mouse events can be set to the correct coordinates.
You have to set Change the size of text, apps, and other items to 100% in display settings.
For IE 11, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates.
For 32-bit Windows installations, the key you have to look in the registry is :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE
For 64-bit Windows installations, the key is :
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE
The FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present.
Native Events : The advantage of using native events is that it does not rely on the JavaScript sandbox, and it ensures proper JavaScript event propagation within the browser. However, there are currently some issues with mouse events when the IE browser window does not have focus, and when attempting to hover over elements.
Browser Focus : IE itself appears to not fully respect the Windows messages we send the IE browser window (WM_MOUSEDOWN and WM_MOUSEUP) if the window doesn't have the focus.
You can find a detailed discussion on Native Events and Browser Focus here.
Now, you have to configure all these parameters through DesiredCapabilities Class as follows :
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability("ignoreProtectedModeSettings",1);
cap.setCapability("IntroduceInstabilityByIgnoringProtectedModeSettings",true);
cap.setCapability("nativeEvents",true);
cap.setCapability("browserFocus",true);
cap.setCapability("ignoreZoomSetting", true);
cap.setCapability("requireWindowFocus","true");
cap.setCapability("INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS", true);
As per Best Programming practices Thread.sleep(1000); is a huge No as it degrades the Test Performance
Now, as you are aware that the Browser Clients lags the WebDriver instance so we have to often sync up them. So before you collect the windowHandles you have to induce WebDriverWait as follows for which you can find a detailed discussion here :
WebElement popup= driver.findElement(By.name("popup"));
popup.click();
new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> windowHandles = driver.getWindowHandles();
System.out.println(windowHandles);
Update
I can see from your comments :
"Enable Enhanced Protected Mode" is unchecked in IE options. – Renjith Jan 9 at 7:26
Here is the exert from #JimEvans sensetional blog on Protected Mode settings and the Capabilities hack where #JimEvans nails the context in a clear and unambiguous term :
When the rewritten IE driver was first introduced, it was decided that it would enforce its required Protected Mode settings, and throw an exception if they were not properly set. Protected Mode settings, like almost all other settings of IE, are stored in the Windows registry, and are checked when the browser is instantiated. However, some misguided IT departments make it impossible for developers and testers to set even the most basic settings on their machines.
The driver needed a workaround for people who couldn't set those IE settings because their machine was overly locked down. That's what the capability setting is intended to be used for. It simply bypasses the registry check. Using the capability doesn't solve the underlying problem though. If a Protected Mode boundary is crossed, very unexpected behavior including hangs, element location not working, and clicks not being propagated, could result. To help warn people of this potential problem, the capability was given big scary-sounding names like INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS in Java and IntroduceInstabilityByIgnoringProtectedModeSettings in .NET. We really thought that telling the user that using this setting would introduce potential badness in their code would discourage its use, but it turned out not to be so.
If you are able to set the Protected Mode settings of IE, and you are still using the capability you are risking the stability of your code. Don't do it. Set the settings. It's not that hard.
Here is how you need to set the Protected Mode settings :
Here is another discussion on Selenium IEServerDriver not finding new windows for IE9 where the solution was Turning on Compatibility Mode
Window handling issue, is mainly because of protected mode settings. Either enable protected mode for all the zones or disable it for all the zone and try.
Dunno what is Set, but I tested with following code
while (true)
{
int qw = ololo.WindowHandles.Count;
string[] wh = ololo.WindowHandles.ToArray();
ololo.FindElement(By.LinkText("Помощь")).Click();
Thread.Sleep(1000);
}
And it worked perfectly.
On IE11, "Enable Protected Mode" setting on the browser is key - can be either ON or OFF (for all zones).
Other settings on driver capabilities didn't matter (in my case) - following worked just as fine:
caps.setCapability("ignoreZoomSetting", false);
caps.setCapability("nativeEvents", false);
caps.setCapability("ignoreProtectedModeSettings", false);

How to handle overlay/popup window using selenium webdriver

I am trying to automate initial configuration(of my server) through webpage. After hitting my server ip https:/localhost:4443 and entering my credentials ,i get a window to change password(overlay/popup window).
Problem:- if i browse the same ip from another m/c or from another browser , i get a window over window i.e one more window over change password window(Please click the link to see the screenshot).
What i tried is to get the handle of the window but its not working, its providing one handle only.
**Its not frame also.
HTML code -- https://dl.dropboxusercontent.com/u/91420517/Html_Code.JPG
Here's my code
WebDriver driver=new FirefoxDriver();
driver.get("https://localhost:4443/ControlPoint/");
driver.findElement(By.xpath("//*[#id='name']")).sendKeys("xxxxxx");
driver.findElement(By.xpath("//*[#id='pass']")).sendKeys("xxxxxx");
driver.findElement(By.xpath("//*[#id='loginForm123']/div[6]/div[1]/div")).click();
Set<String> winIds = driver.getWindowHandles();
System.out.println("Total Windows --- " + winIds.size()); // its resulting the size as 1 which is not correct.
Iterator<String> it = winIds.iterator();
String mainWin=it.next();
String changeWin=it.next();
String shareWin =it.next();
driver.switchTo().window(shareWin);
String warning = driver.findElement(By.xpath("html/body/div[4234]/div[1]/span")).getText(); // to get the text on 3 window
System.out.println(warning);
How to resolve this issue .Please help. Any other way to click on buttons on window 3.
If the additional window is opened asynchronously, then possibly you are checking for it (with getWindowHandles()) too early, before it has been created - this is a common issue with Selenium tests and asynchronous page updates.
If this is the issue, it can be solved by trying a few times with a wait in between, checking each time whether a new window has appeared.

Categories