Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I have a web page that opens a div when you click a button. This div allows you to drag a file from your desktop onto its area; the file then gets uploaded to the server. I'm working with the Ruby implementation of Selenium.

By using the JavaScript debugger in Firefox, I can see that an event called "drop" is being passed to some JavaScript code "handleFileDrop(event)". I presume that if I were to create a mock event and fire it somehow that I could trigger this code.

If found an interesting article that seemed to point me in a promising direction, but I'm still short of figuring it all out. I am able to pass JavaScript to the page using Selenium's get_eval method. Calling methods using this.browserbot is getting me the elements I need.

So:

  1. How do I build the file object that needs to be part of the mock drop event?
  2. How do I fire the drop event such that it gets picked up as if I had dropped a file in the div?

1 Answer

0 votes
by (62.9k points)

Here’s a C# code snippet, that should help you:

private void DropImage(string dropBoxId, string filePath)

{

   var javascriptDriver = this.Driver as IJavaScriptExecutor;

   var inputId = dropBoxId + "FileUpload";

 

   // append input to HTML to add file path

   javascriptDriver.ExecuteScript(inputId + " = window.$('<input id=\"" + inputId + "\"/>').attr({type:'file'}).appendTo('body');");

   this.Driver.FindElement(By.Id(inputId)).SendKeys(filePath);

 

   // fire mock event pointing to the inserted file path

   javascriptDriver.ExecuteScript("e = $.Event('drop'); e.originalEvent = {dataTransfer : { files : " + inputId + ".get(0).files } }; $('#" + dropBoxId + "').trigger(e);");

}

Browse Categories

...