Selenium: Drag and Drop from file system to webdriver?

0
0

I have to test a web-application which contains a drag and drop area for uploading files from the local file system. My test environment is based on C#.

For the automation testing I have used Selenium, but it is not possible to drag files from the file system. The upload area is a div tag (no input tag). So what’s the best way to do it? AutoIt (is it possible to drop in a web browser)? Sikuli?

  • You must to post comments
0
0

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.

IWebElement droparea = driver.FindElement(By.Id("droparea"));
DropFile(droparea, @"C:\...\image.png");

static void DropFile(IWebElement target, string filePath, int offsetX = 0, int offsetY = 0) {
if(!File.Exists(filePath))
throw new FileNotFoundException(filePath);
IWebDriver driver = ((RemoteWebElement)target).WrappedDriver;
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
string JS_DROP_FILE = @"
var target = arguments[0],
offsetX = arguments[1],
offsetY = arguments[2],
document = target.ownerDocument || document,
window = document.defaultView || window;
var input = document.createElement('INPUT');
input.type = 'file';
input.style.display = 'none';
input.onchange = function () {
var rect = target.getBoundingClientRect(),
x = rect.left + (offsetX || (rect.width >> 1)),
y = rect.top + (offsetY || (rect.height >> 1)),
dataTransfer = { files: this.files };
['dragenter', 'dragover', 'drop'].forEach(function (name) {
var evt = document.createEvent('DragEvent');
evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
evt.dataTransfer = dataTransfer;
target.dispatchEvent(evt);
});
setTimeout(function () { document.body.removeChild(input); }, 25);
};
document.body.appendChild(input);
return input;
"
;
IWebElement input = (IWebElement)jse.ExecuteScript(JS_DROP_FILE, target, offsetX, offsetY);
input
.SendKeys(filePath);
wait
.Until(ExpectedConditions.StalenessOf(input));
}
  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website