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;
}
Related
I am trying to make a simple test to test the login form of a website. When I initialize the element Selenium finds it but if I try to click on it or check if its Displayed I either get an exception that the element is not visible or False for the Displayed.
The page: http://www.officemate.co.th/
My code:
IWebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("http://www.officemate.co.th");
IWebElement openSignUp = driver.FindElement(By.CssSelector("body > div:nth-child(6) > div > div:nth-child(3) > ul > li.dropdown > a"));
openSignUp.Click();
IWebElement usernameField = driver.FindElement(By.Id("UserId"));
usernameField.SendKeys("SomeUser");
Console.WriteLine(usernameField.Displayed);
try following code. i have tested it is working fine.
try
{
ChromeDriver driver = new ChromeDriver(#"C:\Users\Muhammad USman\Downloads\chromedriver_win32");
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
//now i changed path for login.
driver.Navigate().GoToUrl("https://www.officemate.co.th/Account/Login");
//full specified xPath of eache element. is here whihc i'll use know.
//https://www.officemate.co.th/Account/Login
var email = #"/html/body/div[9]/div/fieldset/form/div[1]/div/input";
var password = #"/html/body/div[9]/div/fieldset/form/div[2]/div/input";
var check = #"/html/body/div[9]/div/fieldset/form/div[3]/div/input[1]";
var login = #"/html/body/div[9]/div/fieldset/form/div[4]/div/button";
IWebElement usernameField = driver.FindElement(By.XPath(email));
usernameField.Clear();
usernameField.SendKeys("SomeUser#gmail.com");
Console.WriteLine(usernameField.Displayed);
IWebElement pass = driver.FindElement(By.XPath(password));
pass.Clear();
pass.SendKeys("Some!password");
//Check box
var checkBox = driver.FindElement(By.XPath(check));
if (!checkBox.Selected)
{
checkBox.Click();
}
driver.FindElement(By.XPath(login)).Click();
if (driver.FindElements(By.XPath("/html/body/div[9]/div/fieldset/form/div[1]/p")).Count > 0)
{
//invalid login error message
var errorMessage = driver.FindElement(By.XPath("/html/body/div[9]/div/fieldset/form/div[1]/p")).Text;
}
}
catch (Exception exp)
{
throw;
}
if any issue then let me know.
Thanks.
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//
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);
}
I am trying to click on the object, to show the list of value pop-up.
I used the following script, but unable to populate the list value pop-up.
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
Thread.sleep(1000L);
Is there any other way to click and wait for the object?
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
There are other conditions like visibilityOf so choose the one which suits you most - documentation here.
String mainWindowHandle = driver.getWindowHandle();
System.out.println(mainWindowHandle);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(OR.getProperty(Object)));
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
PageUtil.sleep(3000);
Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite = s1.iterator();
while (ite.hasNext()) {
String popupHandle = ite.next().toString();
System.out.println(popupHandle + " Present Pop Up window name");
if (!popupHandle.contains(mainWindowHandle)) {
driver.switchTo().window(popupHandle);
}
}
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
Driver.findElement(By.id("yourId")).click();
driver.switchTo().window(mainWindowHandle);
After clicking you can wait using FluentWait,
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
refer this for more info
I'm not quite familiar with java syntax, but I'll give you php code and you can write similar. The idea is to find HTML element by tag and get it's id BEFORE YOU CLICK. Then AFTER THE CLICK wait for the id to change.
It looks like this:
class MySeleniumCondition extends WebDriverExpectedCondition{
public static function htmlElementIdIsNot($htmlElementId) {
return new WebDriverExpectedCondition(
function ($driver) use ($htmlElementId) {
$htmlElement = $driver->findElement(WebDriverBy::tagName('html'));
return $htmlElementId != $htmlElement->getId();
}
);
}
}
// .............. somehere in a class:
public function waitForNewPage($oldHtmlElementId, $time = 10){
try{
$this->driver->wait($time)->until(
MySeleniumCondition::htmlElementIdIsNot(
$oldHtmlElementId
)
);
return true;
}catch(TimeOutException $e){
return false;
}
}
// use this only when you are sure the page will reload
public function clickAndWait(WebDriverBy $locator, $time = 10){
$webElement = $this->driver->findElement($locator);
$oldHtmlElement = $driver->findElement(WebDriverBy::tagName('html'));
$oldHtmlElementId = $oldHtmlElement->getId();
$webElement->click();
$this->waitForNewPage($oldHtmlElementId, $time);
return true;
}
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)