问题
I am writing following Ruby code in Selenium Webdriver script to enable a disabled field on UI through Javascript executor.
browser.execute_script("browser.find_element(:xpath,'/html/body/div[5]/div/div[3]/div[2]/div[2]/div/div/div/div/div/div/input'.disabled = false")
But facing,
`handleEvaluateEvent': syntax error (Selenium::WebDriver::Error::JavascriptError)
What could be wrong with my syntax?
Any Help will be appreciated.
Thanks! Abhishek
回答1:
Problem
The problem with the line:
browser.execute_script("browser.find_element(:xpath,'/html/body/div[5]/div/div[3]/div[2]/div[2]/div/div/div/div/div/div/input'.disabled = false")
Is that it is trying to execute selenium-webdriver code instead javascript - ie browser.find_element is not javascript.
Solution
Instead, do the following:
input_field = browser.find_element(:xpath, '/html/body/div[5]/div/div[3]/div[2]/div[2]/div/div/div/div/div/div/input')
browser.execute_script('arguments[0].removeAttribute("disabled");', input_field)
Note that:
- We can locate the element using selenium-webdriver and then pass that element for use in
execute_script(as thearguments[0]). - To make a field no longer disabled, you actually need to remove the disabled attribute (rather than setting its value to false).
- You should be careful with using such an explicit xpath as it can be quite brittle - eg one small change will break it.
回答2:
javascript code is independent of binding language, try below
js.executeScript("document.getElementByID('name').value = arguments[0]","John");
来源:https://stackoverflow.com/questions/23117839/enabling-a-disabled-field-using-javascript-executor-for-selenium-webdriver-ruby