Selenium Javascriptexecutor (edge/ie) not changing the value of an input field

65 views Asked by At

am using javascriptexecutor with Selenium (IEdriver used on Edge (IE compatibility)). There is a input with w BROWSE button that brings up a Windows file search. (See picture). Selenium can't handle Windows file browser.

The HTML looks like this

<span class="options">
    <input id="importSource" title="Source" size="50" type="file" 
     name="importSource" requiredfield="1">
</span>

Doing a sendKeys(file) to the element will bring up the file browser. I wanted to use JavascriptExecutor, so I did

[![enter image description here][1]][1]WebElement ele = driver.findElement(By.xpath("//input[@id='importSource']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
String script = "arguments[0].setAttribute('value', '" + fileName + "');";
jse.executeScript(script, ele);

fileName is the name of a file. But when I look at the box it is empty and when I inspect ele.getAttribute("value") it is blank.

If I manually click browse and select a file and do an inspect ele.getAttribute("value") it shows the filename. So setting it should work but doesn't.

is there some reason the Javascript is not working? The value of ele is not null as I can get the attribute. (In the picture I removed any company-specific confidential info, but it is just text).

1

There are 1 answers

4
Xudong Peng On

As far as I know, this is by design. You cannot set file input via JavaScript as this is a security violation. Therefore you cannot achieve this requirement by executing scripts on the page.

But sendKeys work. Because this method bypasses security restrictions, it is an operating system-level event and is not browser-specific. If it is just a simple text input element, this requirement can be easily achieved through javascript. But input element of file type will call the file system.

Just refer to this similar case and relevant doc:

how does selenium webdriver upload files to the browser?

https://aosabook.org/en/v1/selenium.html