Selenium: How to drag and drop in Chrome using C# - selenium

The below code works in Firefox but not in Chrome. From what I could find online it seems that Actions.DragAndDrop does not work with Chrome. I am trying to move SVG elements.
Is there an alternative?
var action = new Actions(driver);
action
.DragAndDropToOffset(middle, 100, 100)
.Build()
.Perform();
Selenium.Webdriver: v3.141.0
Selenium.Webdriver.ChromeDriver: v76.0.3809.68
Selenium.Firefox.Webdriver: v0.24.0
Chrome: Version 76.0.3809.100 (Official Build) (64-bit)

This is what I use in Chrome. Remember when using drag and drop you need a starting element to click, and a second element where you are going to drop it.
Call:
var ele1 = Driver.FindElement(By.Xpath("//button[#class='cz2__images__image-content cz2__images--draggable']"));
var ele2 = Driver.FindElement(By.Xpath("//button[#class='Destination']"));
DragAndDrop(ele1, ele2);
Method:
public static void DragAndDrop(IWebElement element1, IWebElement element2)
{
WaitForElementEnabled(element1);
WaitForElementEnabled(element2);
var builder = new Actions(Driver);
var dragAndDrop = builder.ClickAndHold(element1).MoveToElement(element2).Release(element1).Build();
dragAndDrop.Perform();
}
or....
public static void test ()
{
var test1 = _webDriver.FindElement(By.Id("myid"));
var test2 = _webDriver.FindElement(By.Id("myid2"));
Actions builder1 = new Actions(_webDriver);
IAction dragAndDrop1 = builder1.ClickAndHold(test1).MoveToElement(test2).Release(test1).Build();
dragAndDrop1.Perform();
}

public void DragAndDropItem(IWebElement from, IWebElement to)
{
Actions action = new Actions(_driver);
action.DragAndDrop(from, to).Build().Perform();
}

Related

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 handle the pop-up as webpage and alert both simultaneously?

Please help me to fill this form and then going on to the website along with handling the alert.
Here is my code which is not working:
public class FirstCry {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\CP-SAT\\Chromedriver\\chromedriver.exe");
WebDriver a = new ChromeDriver();
a.get("http://www.firstcry.com/");
Thread.sleep(5000L);
a.manage().window().maximize();
String k = a.getPageSource();
System.out.println(k);
WebDriverWait Wait = new WebDriverWait(a, 30);
Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='amt']/div[2]/div[1]/div[1]/div[3]/div")));
WebElement b = a.findElement(By.xpath(".//*[#id='amt']/div[2]/div[1]/div[1]/div[3]/div"));
b.click();
}
}
In your website popup present inside an iframe with id iframe_Login, you need to switch that iframe before finding the close button of the popup as below :-
//Create this prefs to handle notification popup
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
//Initialize chrome option to add prefs
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
//Now initialize chrome driver with chrome option to handle notification alert
WebDriver a = new ChromeDriver(options)
a.get("http://www.firstcry.com/");
a.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(a, 30)
//Now find iframe and switch to it
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe_Login"));
//Now find the popup close button
WebElement b = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class = '_pop_close _pop_reg_bg']")));
b.click();
//Now switch back from frame to default content for further steps
a.switchTo().defaultContent();
//Now do your further stuff
Hope it helps..:)

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 deal with ModalDialog using selenium webdriver?

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)

Unable to control slider captcha jquery using Selenium Webdrive?

I want to record slider captcha given on our client site.
We have get this concept from other site named as http://www.fmylife.com/signup
This have slider captcha for registration
I have try to use selenium webdriver action builder
public class TestFmylife {
WebDriver driver;
Selenium selenium;
#BeforeMethod
public void startSelenium() {
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.fmylife.com/");
driver.manage().window().maximize();
}
#AfterMethod
public void stopSelenium() {
driver.close();
}
#Test
public void testFmylife() {
selenium.open("/");
selenium.click("link=Sign up");
selenium.waitForPageToLoad("30000");
selenium.type("name=login", "testfmylife");
selenium.type("name=pass", "123#fmylife");
selenium.type("name=passc", "123#fmylife");
selenium.type("name=mail", "testfmylife#gmail.com");
Point MyPoint= driver.findElement(By.xpath("//*[#id='bgSlider']")).getLocation();
WebElement someElement = driver.findElement(By.xpath("//*[#id='bgSlider']"));
System.out.println(MyPoint.x+"--------"+MyPoint.y);
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).moveByOffset(MyPoint.x,(MyPoint.y + 100)).release().build();
dragAndDrop.perform();
selenium.click("css=div.form > div.ok > input[type=\"submit\"]");
}
}
But I can't move slider using this code
Help me to sort this out
I used the dragAndDropBy method of the Actions class (java.lang.Object
org.openqa.selenium.interactions.Actions) and moved the slider by 200 points horizontally . Please give the following code a try:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fmylife.com/signup");
WebElement slider = driver.findElement(By.xpath(".//*[#id='Slider']"));
Actions builder = new Actions (driver);
builder.dragAndDropBy(slider, 200, 0).build().perform();
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
more can be found at - http://code.google.com/p/selenium/wiki/AdvancedUserInteractions
You can use locator as follows -
String xto=Integer.toString(LocatorTo.getLocation().x);
String yto=Integer.toString(LocatorTo.getLocation().y);
Working code-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
If your slider is like mine
with a "slider handle" (an <a/> tag as the box with the value "5ft 5") within a "slider track" (a <div> tag as the long black bar) then the following code will in C# will work to move the slider handle a percentage along the slider track.
public void SetSliderPercentage(string sliderHandleXpath, string sliderTrackXpath, int percentage)
{
var sliderHandle = driver.FindElement(By.XPath(sliderHandleXpath));
var sliderTrack = driver.FindElement(By.XPath(sliderTrackXpath));
var width = int.Parse(sliderTrack.GetCssValue("width").Replace("px", ""));
var dx = (int)(percentage / 100.0 * width);
new Actions(driver)
.DragAndDropToOffset(sliderHandle, dx, 0)
.Build()
.Perform();
}