问题
I am trying to interact the shadow DOM from WATIR code. I used JustinKo's solution as shown below. But it is throwing the following error
Backtrace:: javascript error: Cannot read property 'toLowerCase' of undefined (Selenium::WebDriver::Error::JavascriptError)
when the program meets this line
Watir.element_class_for(element.tag_name.downcase).new(scope, element: element)
My program
require 'watir'
# Monkey-patch due to being unable to check the tag name of the shadow root
class Watir::Browser
def wrap_element(scope, element)
Watir.element_class_for(element.tag_name.downcase).new(scope, element: element)
rescue Selenium::WebDriver::Error::UnknownError # need a better rescue
Watir::Element.new(scope, element: element)
end
end
def expand_root_element(element, browser)
browser.execute_script("return arguments[0].shadowRoot", element)
end
b=Watir::Browser.new
b.goto 'http://alis-core-lin01:8082/core_pl_env5/alis#alis'
element=b.element(xpath: "//vaadin-text-field[@id='user.name']")
shadow_dom=expand_root_element(element,b)
shadow_dom.text_field.set 'Raj'
puts 'Raj'
HTML
回答1:
There's no real good answer here at this point. The initial problem is that a shadow dom attached to an element actually doesn't have a tag name. Hence Justin's monkey patch. But with updates, that patch no longer works. The new problem is that shadow dom's are attached to real elements, but the shadowRoot itself is not a real element. It's like a quasi-element.
- The error is now a
Selenium::WebDriver::Error::JavascriptError
, so your rescue line needs updated for the correct error. - Even if you fix that, you'll get more errors
javascript error: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
This is the result of an internal API call on the wire protocol. For example, I traced the error toselenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:81
The API call returns an internal 500 error with a payload of"{"value":{"error":"javascript error","message":"javascript error: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.\n (Session info: chrome=87.0.4280.88)"
I do not know how to get around this.
来源:https://stackoverflow.com/questions/64768912/javascript-error-cannot-read-property-tolowercase-of-undefined