1

I am using C# and Selenium to navigate a site and was wondering how to pass variables into my JavaScriptExecutor command. If I write it like this:

((IJavaScriptExecutor)webdriver).ExecuteScript("document.getElementByID('text box1').value = 'hello'");

That works fine but when I try to pass it variables it says they are not defined:

var elementID = "text box1"
var fieldValue = "hello"
((IJavaScriptExecutor)webdriver).ExecuteScript("document.getElementByID(elementID).value = fieldValue");

1 Answers1

0

To pass variables into a JavaScriptExecutor command you can use the following solution:

var elementID = "text box1"
var fieldValue = "hello"
((IJavaScriptExecutor)webdriver).ExecuteScript("document.getElementById('" + elementID + "').value ='" + fieldValue + "'");

PS: It's document.getElementById() and not document.getElementByID(). Check the case of Id.


References

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352