My Thoughts: Handling "drag and drop" actions using WebDriver(Selenium 2)

Tuesday, June 19

Handling "drag and drop" actions using WebDriver(Selenium 2)


Automating rich web application is even more interesting since it involves advanced user interactions.

Say we have a web application which drag an item from one location and then drop it at another location.These kind of drag and drops are cant be automated with one single statement .In WebDriver we have a separatae "Actions" class to handle advanced user interactions(say drag and drop) on web page.

Here is the documentation on how to automate advanced user interactions :
http://code.google.com/p/selenium/wiki/AdvancedUserInteractions

Here is the sample code using TestNG framework
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class draganddrop {
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
  FirefoxProfile profile = new FirefoxProfile();
  profile.setEnableNativeEvents(true);
  driver = new FirefoxDriver(profile);
 }

 @Test
 public void start1(){
  driver.get("http://jqueryui.com/droppable/");
  driver.switchTo().frame(0);  
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  WebElement dragElement=driver.findElement(By.id("draggable"));
  WebElement dropElement=driver.findElement(By.id("droppable"));
    
  Actions builder = new Actions(driver);  // Configure the Action
  Action dragAndDrop = builder.clickAndHold(dragElement)
    .moveToElement(dropElement)
    .release(dropElement)
    .build();  // Get the action
    dragAndDrop.perform(); // Execute the Action
 }
}

28 comments:

  1. Very good info. Lucky me I recently found your site by
    accident (stumbleupon). I've saved as a favorite for later!
    Also visit my homepage - local searh engine

    ReplyDelete
  2. Hi, when I am executing the following error I am getting. What may be the issue, please let me know.

    org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: Given coordinates (576, 422) are outside the document. Error: MoveTargetOutOfBoundsError: The target location (576, 422) is not on the webpage.

    ReplyDelete
  3. JqeryUi has an updated new site. I just updated the code.Now try it will work now.

    ReplyDelete
  4. Hi i have looked into this code and modified as such that when i clickAndHold() i want a screenshot before release(). I have added a method Screenshot() extending Actions class. Can you suggest will this work. coz wen i do this, the Screenshot() captured is before clickAndHold(). How to do this? Any idea?

    ReplyDelete
  5. You can do this by using two different Actions classes.

    Here is the sample code :

    WebElement dragElement=driver.findElement(By.id("draggable"));
    WebElement dropElement=driver.findElement(By.id("droppable"));

    Actions builder = new Actions(driver);
    Action dragAndHold= builder.clickAndHold(dragElement)
    .build();
    dragAndHold.perform();

    File beforeImage = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(beforeImage, new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\beforeimage.png")) ;


    Actions builder1 = new Actions(driver);
    Action dragAndDrop = builder1.clickAndHold(dragElement)
    .moveToElement(dropElement)
    .release(dropElement)
    .build(); // Get the action
    dragAndDrop.perform();


    File afterImage = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(afterImage, new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\afterimage.png")) ;

    ReplyDelete
  6. Thanks :) it worked

    ReplyDelete
  7. Hi Vamshi,


    I have one more query related to this. Suppose their is a focus skin which displays only on clickAndHold(), how do i capture the screenshot of that focus skin before release()? I worked with this above code, but cudn't work out.


    Any suggestions how to go with this?


    Thanks
    Nitin

    ReplyDelete
  8. Nitin,

    Do you have any example site ?

    ReplyDelete
  9. You can try below html code:





    div#n1:active{
    border: 0px solid #000000;


    font : normal normal 16px Helvetica ;
    color: yellow;
    }




    I have a bike

    I have a car





    Here exact scenario i have put. You can check that, when i clickAndHold on checkbox, the color changes to "yellow". When i release it gets back to original.


    I think this example would be simpler to understand my issue.


    Thanks

    ReplyDelete
  10. hi vamshi kurra,


    i am getting the same error as raju got , could let me know why it is occuring

    ReplyDelete
  11. Hi Vamshi!

    I found what the issue is, it's problem with Selenium driver and the firefox version. I have ff of version 21 and Selenium 2.32 doesn't support this action sequence on this version of browser. So on upgrading to 2.33 Selenium server, it works fine.

    ReplyDelete
  12. Hey thanks for the info Nitin :)

    ReplyDelete
  13. Jack,


    Can you try by updating your jars?

    ReplyDelete
  14. Can u please tell me what mistake am i doing here. Because i coulnt able to drag the element. always i am getting error saying that unable to locate the element.

    Html element:

    Which i need to drag the element





    Name





    First Name



    Which i need to drop the element

    Here is div contains the iFrame



    Here is my code:

    driver.switchTo().frame(0);

    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    /*WebElement dragElement = new FluentWait(driver)

    .withTimeout(60,TimeUnit.SECONDS)

    .pollingEvery(5,TimeUnit.SECONDS)

    .ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(("//*[@id='companyName_pannel']")))); */

    WebElement dragElement=driver.findElement(By.xpath("//*[@id='fullName_pannel']"));

    /*WebElement dropElement = new FluentWait(driver)

    .withTimeout(60,TimeUnit.SECONDS)

    .pollingEvery(5,TimeUnit.SECONDS)

    .ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(("//*[@id='formcontent']")))); */

    WebElement dropElement=driver.findElement(By.xpath("//*[@id='formcontent']"));

    Actions builder = new Actions(driver); // Configure the Action

    Action dragAndDrop = builder.clickAndHold(dragElement)

    .moveToElement(dropElement)

    .release(dropElement)

    .build(); // Get the action

    dragAndDrop.perform(); // Execute the Action

    //Thread.sleep(6000);

    ReplyDelete
  15. Do you have the public site url on which you are performing this test ?

    ReplyDelete
  16. Nope :(

    I have attached a screenshot. Let me know if this is helps.

    ReplyDelete
  17. From screen , it looks like the area where you would like to drag an element is inside another frame. {I might be wrong} . If it happens to be inside iframe then make sure you switch to proper iframe before identifing the element.

    http://www.mythoughts.co.in/2012/05/permission-denied-for-to-get-property.html

    http://www.mythoughts.co.in/2012/05/getting-total-noof-checkboxestextboxesd.html

    ReplyDelete
  18. Ya Vamshi your correct its a frame only. How can i drag from one iframe and drop it in another iframe?

    ReplyDelete
  19. Drag and drop should work even in iframes.
    Make sure you identify the drag and drop elements correctly with proper id or xpath .

    ReplyDelete
  20. Hey,
    driver.switchTo().frame(0);

    Is this will work with frame?

    ReplyDelete
  21. If you know the frame id then use id itself.

    frame(0) may or may not work because 0 is the index of frame. In your page try to find the frame index of frame you are working on.

    use the below code to get all iframes in the page



    driver.get("https://www.facebook.com/googlechrome/app_158587972131");
    List totaliFrames=driver.findElements(By.tagName("iframe"));
    System.out.println("total links "+totaliFrames.size());

    ReplyDelete
  22. Ya i have tired. Its click on that particular element which i need to drag. But its not dropping. :(

    ReplyDelete
  23. Madiraju Krishna ChaitanyaTuesday, October 01, 2013

    Hi Vamsi,Good Morning.Thanks a LOT for creating this WebSite for us who are learners of selenium.Please keep Posting the articles/posts that you learn/come across.All the Best.Thanks Again.~chaitanya

    ReplyDelete
  24. Madiraju Krishna ChaitanyaTuesday, October 01, 2013

    Hi Vamshi,Good Morning.I would like to Thank You for this wonderful site that you have given us who are learning Selenium.Please continue with your Great Work.Thanks Again.~Chaitanya

    ReplyDelete
  25. Thanks Chaitanya. I really appreciate it :)
    Wish you luck

    ReplyDelete
  26. you have explained it to the very basics. Thank you. it worked. :) if you have time check up on my blog about #Selenium. i would love to see ya comments. http://anjiztechshare.blogspot.com/

    ReplyDelete
  27. I must say your blog pretty much good and well organized :)

    ReplyDelete
  28. Hi Vamshi, I want to drag and drop in a pop up.
    Here is the html code of that:
    Please let me know as soon as possible.

    ReplyDelete