mulla mulla - 3 months ago 44
Java Question

Drag and Drop functionality is not working in selenium Webdriver

I am trying to learn selenium. I have the following site where the drag and drop functionality is available http://html5demos.com/drag#. I am trying to do the drag and drop using the below codes. But not able to do the same. Any help on this will be appreciated.

Code 1

System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\drivers\\IEDriverServer.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://html5demos.com/drag");
driver.manage().window().maximize();
List<WebElement> ele1=driver.findElements(By.id("bin"));
System.out.println(ele1.size());
System.out.println(ele1.get(0).isDisplayed());
WebElement ele2=driver.findElement(By.id("one"));
System.out.println(ele1.get(0).isDisplayed());
System.out.println(ele2.isDisplayed());
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(ele2)
.moveToElement(ele1.get(0))
.release(ele2)
.build();
dragAndDrop.perform();


Code 2

(new Actions(driver)).dragAndDrop(ele2, ele1.get(0)).perform();


Code 3

Actions builder = new Actions(driver);
builder.dragAndDropBy(ele2, -50, 35).perform();

Answer

found out a JavaScript which does the work drag and drop in HTML5

final String java_script =
"var src=arguments[0],tgt=arguments[1];var dataTransfer={dropEffe" +
"ct:'',effectAllowed:'all',files:[],items:{},types:[],setData:fun" +
"ction(format,data){this.items[format]=data;this.types.append(for" +
"mat);},getData:function(format){return this.items[format];},clea" +
"rData:function(format){}};var emit=function(event,target){var ev" +
"t=document.createEvent('Event');evt.initEvent(event,true,false);" +
"evt.dataTransfer=dataTransfer;target.dispatchEvent(evt);};emit('" +
"dragstart',src);emit('dragenter',tgt);emit('dragover',tgt);emit(" +
"'drop',tgt);emit('dragend',src);";


driver.get("http://html5demos.com/drag");
WebElement LocatorFrom =driver.findElement(By.id("three"));
WebElement LocatorTo = driver.findElement(By.id("bin"));
((JavascriptExecutor)driver).executeScript(java_script, LocatorFrom, LocatorTo);