File Upload using JavaScript & Selenium

Uploading a file using selenium is bit tricky.
As sendkeys() method works in most of the cases to upload a file. You just need to pass the file path in sendkeys() method and it uploads the file.

However, in few web application, you might get following error : ElementNotInteractableException, when you try to upload a file using sendkeys() method.

ElementNotInteractableException indicates that element is available in DOM but selenium is unable to interact with it.

How Java script will help to upload a file?
When you upload a file on web page, there is text box hidden in an application which stores the file path that you select from your local machine and when you execute sendkeys() command to enter file path into that hidden text box, selenium might throw ElementNotInteractableException.

Solution:
Before executing sendkeys() method, make that hidden text box visible using JavaScriptExecutor:

WebElement element = driver.findElement(locator);
JavascriptExecutor js = (JavascriptExecutor) driver;
// Setting value for "style" attribute to make textbox visible
js.executeScript("arguments[0].style.display='block';", element);
driver.findElement(locator).sendKeys("D:\\testImage.png");

Above code will make the hidden text box visible for selenium and then sendkeys() command will enter the file path into that text box.

If you really like the information provided above, please don’t forget to hit a like on Facebook Page, you can also leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *