How to Automate Drag & Drop Functionality Using Selenium Webdriver Java

How to perform Drag & Drop functionality in Selenium WebDriver where we need to drag files from local machine to a web portal?

I was searching for a method by which we can drag and drop file directly to webpage.

One of my friends just told me that we cannot do it but we can do this within webpage using Robot() class. Below is the code:

package com;
import java.awt.Robot;
import java.awt.event.InputEvent;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Robott {

@Test
public void DragnDrop() throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("http://gmail.com");
Robot r = new Robot();
Thread.sleep(4000);
r.mouseMove(400, 350);
r.mousePress(InputEvent.BUTTON1_MASK);
Thread.sleep(2000);
r.mouseMove(500, 350);
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
}

By using Robot() class we can do mouse and keyboard actions, so it may work here.

How to drag and drop in selenium when there are multiple elements

I think you should create a new instance of Actions interface every time you use it.

Try below code with my personalized drag and drop functionality:

List<WebElement> reportFields = driver.findElements(By.className("reportDataFields"));
WebElement target = driver.findElement(By.id("rptDataSections"));

for (int i = 0; i < reportFields.size(); i++) {
if (reportFields.get(i).getText().equals(Section)) {
WebElement draggedFrom = reportFields.get(i);
new Actions(driver)
.moveToElement(draggedFrom)
.pause(Duration.ofSeconds(1))
.clickAndHold(draggedFrom)
.pause(Duration.ofSeconds(1))
.moveByOffset(1, 0)
.moveToElement(target)
.moveByOffset(1, 0)
.pause(Duration.ofSeconds(1))
.release().perform();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Selenium: Drag and Drop from file system to WebDriver?

It's possible with Selenium alone, but it's not simple. It requires to inject a new INPUT element in the page to receive the file through SendKeys. Then, the script needs to simulate the drop by sending the dragenter, dragover, drop events to the targeted area.

static void Main(string[] args)
{
var driver = new ChromeDriver();
driver.Url = "https://react-dropzone.js.org/";

IWebElement droparea = driver.FindElementByCssSelector("[data-preview='Basic example'] [style]");
DropFile(droparea, @"C:\Users\florent\Desktop\capture.png");

driver.Quit();
}

const string JS_DROP_FILE = "for(var b=arguments[0],k=arguments[1],l=arguments[2],c=b.ownerDocument,m=0;;){var e=b.getBoundingClientRect(),g=e.left+(k||e.width/2),h=e.top+(l||e.height/2),f=c.elementFromPoint(g,h);if(f&&b.contains(f))break;if(1<++m)throw b=Error('Element not interractable'),b.code=15,b;b.scrollIntoView({behavior:'instant',block:'center',inline:'center'})}var a=c.createElement('INPUT');a.setAttribute('type','file');a.setAttribute('style','position:fixed;z-index:2147483647;left:0;top:0;');a.onchange=function(){var b={effectAllowed:'all',dropEffect:'none',types:['Files'],files:this.files,setData:function(){},getData:function(){},clearData:function(){},setDragImage:function(){}};window.DataTransferItemList&&(b.items=Object.setPrototypeOf([Object.setPrototypeOf({kind:'file',type:this.files[0].type,file:this.files[0],getAsFile:function(){return this.file},getAsString:function(b){var a=new FileReader;a.onload=function(a){b(a.target.result)};a.readAsText(this.file)}},DataTransferItem.prototype)],DataTransferItemList.prototype));Object.setPrototypeOf(b,DataTransfer.prototype);['dragenter','dragover','drop'].forEach(function(a){var d=c.createEvent('DragEvent');d.initMouseEvent(a,!0,!0,c.defaultView,0,0,0,g,h,!1,!1,!1,!1,0,null);Object.setPrototypeOf(d,null);d.dataTransfer=b;Object.setPrototypeOf(d,DragEvent.prototype);f.dispatchEvent(d)});a.parentElement.removeChild(a)};c.documentElement.appendChild(a);a.getBoundingClientRect();return a;";

static void DropFile(IWebElement target, string filePath, double offsetX = 0, double offsetY = 0)
{
if (!File.Exists(filePath))
throw new FileNotFoundException(filePath);

IWebDriver driver = ((RemoteWebElement)target).WrappedDriver;
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;

IWebElement input = (IWebElement)jse.ExecuteScript(JS_DROP_FILE, target, offsetX, offsetY);
input.SendKeys(filePath);
}

Source: https://gist.github.com/florentbr/349b1ab024ca9f3de56e6bf8af2ac69e



Related Topics



Leave a reply



Submit