How to deal with ModalDialog using selenium webdriver? - selenium

I am unable to switch to Modal Dialog of given example
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm
I don't know how to get element on modal Dialog

Use
following methods to switch to modelframe
driver.switchTo().frame("ModelFrameTitle");
or
driver.switchTo().activeElement()
Hope this will work

What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());

Try the below code. It is working in IE but not in FF22. If Modal dialog found is printed in Console, then Modal dialog is identified and switched.
public class ModalDialog {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm");
String parent = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement push_to_create = wait.until(ExpectedConditions
.elementToBeClickable(By
.cssSelector("input[value='Push To Create']")));
push_to_create.click();
waitForWindow(driver);
switchToModalDialog(driver, parent);
}
public static void waitForWindow(WebDriver driver)
throws InterruptedException {
//wait until number of window handles become 2 or until 6 seconds are completed.
int timecount = 1;
do {
driver.getWindowHandles();
Thread.sleep(200);
timecount++;
if (timecount > 30) {
break;
}
} while (driver.getWindowHandles().size() != 2);
}
public static void switchToModalDialog(WebDriver driver, String parent) {
//Switch to Modal dialog
if (driver.getWindowHandles().size() == 2) {
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
System.out.println("Modal dialog found");
break;
}
}
}
}
}

Solution in R (RSelenium):
I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code
Here are methods which worked for me:
Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog
My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()
Sys.sleep(5)
remDr$switchToFrame(date_filter_frame)
Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()

Try this code, include your object names & variable to work.
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
windowids = driver.getWindowHandles();
iter= windowids.iterator();
String main_windowID=iter.next();
String tabbed_windowID=iter.next();
System.out.println("Main Window ID :"+main_windowID);
//switch over to pop-up window
Thread.sleep(1000);
driver.switchTo().window(tabbed_windowID);
System.out.println("Pop-up window Title : "+driver.getTitle());

I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.
WebElement link = // element that will showModalDialog()
// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
"var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
link);
// wait for there to be two windows and choose the one that is
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(final WebDriver driver) {
final String[] windowHandles =
driver.getWindowHandles().toArray(new String[0]);
if (windowHandles.length != 2) {
return false;
}
if (windowHandles[0].equals(parentWindowHandle)) {
driver.switchTo().window(windowHandles[1]);
} else {
driver.switchTo().window(windowHandles[0]);
}
return true;
}
});

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model,
This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

P.S. 1 adding my 2 cents even though the question is too old
public void PressEnterKey()
{
var simulator = new InputSimulator();
simulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
}
you can create a method like the above and call it where it is required.
P.S. 2 - you can change the keyboard inputs as well (like up arrow, down arrow, page down etc)

Related

How to check all opened windows with title in chrome using selenium

In chrome 3 windows opened but without closing any window need to check last open window title
tried driver.getTitle();
but It returns first window title
Reason is that I want get page title and performing any activity on last window.
First you can switch the window and then validate page. You can try this approach:
public void switchwindow() throws InterruptedException {
currentHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allHandles = driver.getWindowHandles();
for (String handle : allHandles) {
if (!handle.equals(currentHandle)) {
driver.switchTo().window(handle);
break;
} else {
driver.switchTo().window(currentHandle);
Thread.sleep(8000);
}
}
}
Switch to parent window:
public void switchToParentWindow() throws InterruptedException {
Thread.sleep(5000);
driver.switchTo().window(currentHandle);
}

How to continue running my testcases in the same window using selenium C#?

Please help me with this.
My second method is dependent on first method and so on.
I am not using driver.quit() or driver.close()
[TestMethod]
public void CheckInAsDcs()
{
Thread.Sleep(2000);
Assert.AreEqual(driver.Title, "NeuTravel");
var selectDropDown = driver.FindElement(By.Id("viewSelect"));
var dcsOption = driver.FindElements(By.TagName("option"))[1];
//checking for dcs in dropdown
var checkForDcs = driver.FindElement(By.Id("viewSelect"));
dcsOption.Click();
Thread.Sleep(2000);
}
[TestMethod]
public void CreateNewRequest()
{
//calling CheckInAsDcs function
CheckInAsDcs();
//waiting for the web elements to load
Thread.Sleep(10000);
//finding CreateNewRequest button and clicking it
var selectCreateNewReq = driver.FindElements(By.TagName("input"));
selectCreateNewReq[0].Click();
}

How to verify whether new tab opened or not in selenium webdriver?

I have a situation where I have to check whether after clicking on a link a new tab is opened or not. If the tab opens I want to check the title as well.
Does anyone have any idea about this.
Here is the same for C#; this is tested and will work whether the link opens in new tab or new window.
var browserTabs = driver.WindowHandles;
driver.SwitchTo().Window(browserTabs[1]);
//check is it correct page opened or not (e.g. check page's title or url, etc.)
// ...
//close tab and get back
driver.Close();
driver.SwitchTo().Window(browserTabs[0]);
Hope this helps anyone who comes across this thread.
Try to switch to a new tab and then verify whether is it correct page or not.
In Java it can be look like:
//get window handlers as list
List<String> browserTabs = new ArrayList<String> (driver.getWindowHandles());
//switch to new tab
driver.switchTo().window(browserTabs .get(1));
//check is it correct page opened or not (e.g. check page's title)
//...
//then close tab and get back
driver.close();
driver.switchTo().window(browserTabs.get(0))
You can use below method to implement the desired wait until the tab is fully loaded.
public static void switchTabs(WebDriver driver, int expectedWindowsCount,int SwitchtoWindow) throws Exception {
(new WebDriverWait(driver, 30)).until(ExpectedConditions.numberOfWindowsToBe(expectedWindowsCount));
ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs2.get(SwitchtoWindow));
}
The method will check how many Active window handlers are available and wait until desired handlers are present and switch to the tab afterwards.
Use wait for no of tabs to open to make sure a new tab is opened
(new WebDriverWait(driver, 30)).until(ExpectedConditions.numberOfWindowsToBe(2));
Then switch to the new tab
protected void switchTabsUsingPartOfUrl(String platform) {
String currentHandle = null;
try {
final Set<String> handles = driver.getWindowHandles();
if (handles.size() > 1) {
currentHandle = driver.getWindowHandle();
}
if (currentHandle != null) {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
break;
}
}
} else {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform)) {
break;
}
}
}
} catch (Exception e) {
System.out.println("Switching tabs failed");
}
}
Call this method and pass parameter a substring of url of the tab you want to switch to
driver.getTitle().equals("Title");
Then verify page title
This would help you if you are doing test automation in Groovy
def browserTabs = driver.getWindowHandles()
driver.switchTo().window(browserTabs[1])
assert //Validate your new page title//

How to check items of the context menu, after right click, Selenium?

I'm writing a test(using selenium) to verify that after a i right click on a particular part of our website, it should show the standard context menu (copy, past, reload, saveAs etc) and not our created context menu.
I need to find a way to check the items on the context menu after the right click, any ideas?
Heres where i am so far...
private IWebDriver driver = null;
private WebDriverWait wait = null;
private Actions action;
[TestInitialize()]
public void Initialize()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://localhost/testwebportal");
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
action= new Actions(driver);
}
[TestMethod]
public void Right_click_brochure_while_zoomed_in_ID_8_2()
{
// click brochure
var clickFirstProduct = driver.FindElement(By.CssSelector("div.MetaSearchBrochureTile:nth-child(1) > div:nth-child(1) > img:nth-child(2)"));
clickFirstProduct.Click();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1500));
// zoom in
var brochurePage = driver.FindElement(By.CssSelector(".p1"));
brochurePage.Click();
action.ContextClick(brochurePage);
// code to check if context menu is not my created right click menu browser,
// by looking at the menu items after the right click.
action.Perform();
}
Ray
If you are looking for the machinary to drive a selenium right click, check out how to do a right click in selenium or how to simulate a right click with code in selenium.
I hope this helps. If I have miss understood your question please let me know. Since you did not give me the HTML structure I have made many assumptions.
ContextOption is an array of string with contains the options expected in the context menu.
What I am doing is comparing the options expected with the optionsdisplayed in the context menu by text. This will return false if any one them is mismatched, less than what you expected or more than what you expected
Please remember to replace the code with proper element locaters.
var actions = new Actions(driver);
WebElement webElement = driver.FindElement(By.XPath("")));
actions.ContextClick(webElement).Perform();
int numberOfOptionPresent = 0;
foreach (var option in ContextOption)
{
IWebElement contextOptions = driver.FindElement(By.XPath(""));
ReadOnlyCollection<IWebElement> totalContextOption = contextOptions.FindElements(By.TagName("li"));
for (int c = 1; c <= totalContextOption.Count; c++)
{
string contextText = driver.FindElement(By.XPath("li[" + c + "]")).Text;
if (contextText == option)
{
if (contextText != "")
{
numberOfOptionPresent++;
}
break;
}
if (totalContextOption.Count == c)
{
return false;
}
}
if (numberOfOptionPresent == ContextOption.Count())
{
return true;
}
return false;
}

How to handle multiple jQuery popup with selenium webdriver

I am working on java with selenium webdriver 2.39, we have application where multiple 'processing' popup is display for 2-5 sec and closed automatically, that is depend on data. Now, the question is how to handle this popup, this popup are jQuery popup. My script can only work further once all this three popup gets open and process data and get closed automatically. However, I can not use wait time as this script is used for load testing using JMeter, hence the process time may take more or less than 5 sec., Is there any way we can know if the popup exist or not on screen? I have used below given sample code but it returns only parent window and it does not identify jQuery popup, using below given code I can get if popup exist or not, but only if it is not jQuery popup. Can anyone help me?
public void FocusOnWindow() throws Exception{
int i=0;
do {
handles=driver.getWindowHandles();//get all windows
iterator = handles.iterator();
if(iterator.hasNext()){
subWindowHandler = iterator.next();
if(subWindowHandler==null){
i=0;
}else if(subWindowHandler!=null){
if(subWindowHandler!=parentWindowHandler){
popup = true;
i=2;
}
}
}
}while(i<2);
if(popup){
do{
handles=driver.getWindowHandles();
iterator = handles.iterator();
Thread.sleep(500);
if(iterator.hasNext()){
subWindowHandler = iterator.next();
if(subWindowHandler!=parentWindowHandler){
if(subWindowHandler==null){
String source = driver.getPageSource();
if(source==null){
i=2;
}
}
}else {
i=0;
}
//System.out.println("No any other popup.");
}
}while (i<2);
}
}
First of all, I'll strongly suggest not to put hard wait at all.
If you are aware of any of the element which is unique and part of post processing pop up screen (i.e. resulted user screen) then make use of selenium waitForElement() API function which intelligently wait for element to appear and once appeared performs further actions.
Take a look at this link which explains the advantages of using it.
And with Java bindings for selenium in place, You can use something like this -
WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/3);
elementOfPage = wait.until(presenceOfElementLocated(By.id("id_of_element")));
Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
return new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
public boolean runScript(){
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript("return jQuery.active==0;");
}
public void FocusOnWindow() throws Exception{
int i=0;
do {
if(!runScript()){
System.out.println("Popup exists");
i++;
}else{
i=5000;
System.out.println("Popup does not exists");
}
}while(i<5000);
}