WebDriverConnection.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /*
  2. * Copyright (c) 2022, Florent Castelli <florent.castelli@gmail.com>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  6. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/JsonObject.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/Vector.h>
  13. #include <LibJS/Runtime/Value.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/Element.h>
  16. #include <LibWeb/HTML/AttributeNames.h>
  17. #include <LibWeb/HTML/BrowsingContext.h>
  18. #include <LibWeb/HTML/HTMLInputElement.h>
  19. #include <LibWeb/HTML/HTMLOptionElement.h>
  20. #include <LibWeb/Page/Page.h>
  21. #include <LibWeb/Platform/EventLoopPlugin.h>
  22. #include <LibWeb/Platform/Timer.h>
  23. #include <WebContent/ConnectionFromClient.h>
  24. #include <WebContent/PageHost.h>
  25. #include <WebContent/WebDriverConnection.h>
  26. namespace WebContent {
  27. static JsonValue make_success_response(JsonValue value)
  28. {
  29. JsonObject result;
  30. result.set("value", move(value));
  31. return result;
  32. }
  33. static JsonValue serialize_rect(Gfx::IntRect const& rect)
  34. {
  35. JsonObject serialized_rect = {};
  36. serialized_rect.set("x", rect.x());
  37. serialized_rect.set("y", rect.y());
  38. serialized_rect.set("width", rect.width());
  39. serialized_rect.set("height", rect.height());
  40. return make_success_response(move(serialized_rect));
  41. }
  42. static Gfx::IntRect compute_window_rect(Web::Page const& page)
  43. {
  44. return {
  45. page.window_position().x(),
  46. page.window_position().y(),
  47. page.window_size().width(),
  48. page.window_size().height()
  49. };
  50. }
  51. // https://w3c.github.io/webdriver/#dfn-get-or-create-a-web-element-reference
  52. static String get_or_create_a_web_element_reference(Web::DOM::Node const& element)
  53. {
  54. // FIXME: 1. For each known element of the current browsing context’s list of known elements:
  55. // FIXME: 1. If known element equals element, return success with known element’s web element reference.
  56. // FIXME: 2. Add element to the list of known elements of the current browsing context.
  57. // FIXME: 3. Return success with the element’s web element reference.
  58. return String::number(element.id());
  59. }
  60. // https://w3c.github.io/webdriver/#dfn-web-element-reference-object
  61. static JsonObject web_element_reference_object(Web::DOM::Node const& element)
  62. {
  63. // https://w3c.github.io/webdriver/#dfn-web-element-identifier
  64. static String const web_element_identifier = "element-6066-11e4-a52e-4f735466cecf"sv;
  65. // 1. Let identifier be the web element identifier.
  66. auto identifier = web_element_identifier;
  67. // 2. Let reference be the result of get or create a web element reference given element.
  68. auto reference = get_or_create_a_web_element_reference(element);
  69. // 3. Return a JSON Object initialized with a property with name identifier and value reference.
  70. JsonObject object;
  71. object.set("name"sv, identifier);
  72. object.set("value"sv, reference);
  73. return object;
  74. }
  75. // https://w3c.github.io/webdriver/#dfn-get-a-known-connected-element
  76. static ErrorOr<Web::DOM::Element*, Web::WebDriver::Error> get_known_connected_element(StringView element_id)
  77. {
  78. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference().
  79. // For now the element is only represented by its ID.
  80. auto element = element_id.to_int();
  81. if (!element.has_value())
  82. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an integer");
  83. auto* node = Web::DOM::Node::from_id(*element);
  84. if (!node || !node->is_element())
  85. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, String::formatted("Could not find element with ID: {}", element_id));
  86. return static_cast<Web::DOM::Element*>(node);
  87. }
  88. static ErrorOr<String, Web::WebDriver::Error> get_property(JsonValue const& payload, StringView key)
  89. {
  90. if (!payload.is_object())
  91. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  92. auto const* property = payload.as_object().get_ptr(key);
  93. if (!property)
  94. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("No property called '{}' present", key));
  95. if (!property->is_string())
  96. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' is not a String", key));
  97. return property->as_string();
  98. }
  99. ErrorOr<NonnullRefPtr<WebDriverConnection>> WebDriverConnection::connect(ConnectionFromClient& web_content_client, PageHost& page_host, String const& webdriver_ipc_path)
  100. {
  101. dbgln_if(WEBDRIVER_DEBUG, "Trying to connect to {}", webdriver_ipc_path);
  102. auto socket = TRY(Core::Stream::LocalSocket::connect(webdriver_ipc_path));
  103. dbgln_if(WEBDRIVER_DEBUG, "Connected to WebDriver");
  104. return adopt_nonnull_ref_or_enomem(new (nothrow) WebDriverConnection(move(socket), web_content_client, page_host));
  105. }
  106. WebDriverConnection::WebDriverConnection(NonnullOwnPtr<Core::Stream::LocalSocket> socket, ConnectionFromClient& web_content_client, PageHost& page_host)
  107. : IPC::ConnectionToServer<WebDriverClientEndpoint, WebDriverServerEndpoint>(*this, move(socket))
  108. , m_web_content_client(web_content_client)
  109. , m_page_host(page_host)
  110. {
  111. }
  112. // https://w3c.github.io/webdriver/#dfn-close-the-session
  113. void WebDriverConnection::close_session()
  114. {
  115. // 1. Set the webdriver-active flag to false.
  116. set_is_webdriver_active(false);
  117. // 2. An endpoint node must close any top-level browsing contexts associated with the session, without prompting to unload.
  118. m_page_host.page().top_level_browsing_context().close();
  119. }
  120. void WebDriverConnection::set_is_webdriver_active(bool is_webdriver_active)
  121. {
  122. m_page_host.set_is_webdriver_active(is_webdriver_active);
  123. }
  124. // 10.1 Navigate To, https://w3c.github.io/webdriver/#navigate-to
  125. Messages::WebDriverClient::NavigateToResponse WebDriverConnection::navigate_to(JsonValue const& payload)
  126. {
  127. dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::navigate_to {}", payload);
  128. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  129. TRY(ensure_open_top_level_browsing_context());
  130. // 2. Let url be the result of getting the property url from the parameters argument.
  131. if (!payload.is_object() || !payload.as_object().has_string("url"sv))
  132. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a string `url`"sv);
  133. URL url(payload.as_object().get_ptr("url"sv)->as_string());
  134. // FIXME: 3. If url is not an absolute URL or is not an absolute URL with fragment or not a local scheme, return error with error code invalid argument.
  135. // FIXME: 4. Handle any user prompts and return its value if it is an error.
  136. // FIXME: 5. Let current URL be the current top-level browsing context’s active document’s URL.
  137. // FIXME: 6. If current URL and url do not have the same absolute URL:
  138. // FIXME: a. If timer has not been started, start a timer. If this algorithm has not completed before timer reaches the session’s session page load timeout in milliseconds, return an error with error code timeout.
  139. // 7. Navigate the current top-level browsing context to url.
  140. m_page_host.page().load(url);
  141. // FIXME: 8. If url is special except for file and current URL and URL do not have the same absolute URL:
  142. // FIXME: a. Try to wait for navigation to complete.
  143. // FIXME: b. Try to run the post-navigation checks.
  144. // FIXME: 9. Set the current browsing context with the current top-level browsing context.
  145. // FIXME: 10. If the current top-level browsing context contains a refresh state pragma directive of time 1 second or less, wait until the refresh timeout has elapsed, a new navigate has begun, and return to the first step of this algorithm.
  146. // 11. Return success with data null.
  147. return make_success_response({});
  148. }
  149. // 10.2 Get Current URL, https://w3c.github.io/webdriver/#get-current-url
  150. Messages::WebDriverClient::GetCurrentUrlResponse WebDriverConnection::get_current_url()
  151. {
  152. dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::get_current_url");
  153. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  154. TRY(ensure_open_top_level_browsing_context());
  155. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  156. // 3. Let url be the serialization of the current top-level browsing context’s active document’s document URL.
  157. auto url = m_page_host.page().top_level_browsing_context().active_document()->url().to_string();
  158. // 4. Return success with data url.
  159. return make_success_response(url);
  160. }
  161. // 11.8.1 Get Window Rect, https://w3c.github.io/webdriver/#dfn-get-window-rect
  162. Messages::WebDriverClient::GetWindowRectResponse WebDriverConnection::get_window_rect()
  163. {
  164. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  165. TRY(ensure_open_top_level_browsing_context());
  166. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  167. // 3. Return success with data set to the WindowRect object for the current top-level browsing context.
  168. return serialize_rect(compute_window_rect(m_page_host.page()));
  169. }
  170. // 11.8.2 Set Window Rect, https://w3c.github.io/webdriver/#dfn-set-window-rect
  171. Messages::WebDriverClient::SetWindowRectResponse WebDriverConnection::set_window_rect(JsonValue const& payload)
  172. {
  173. if (!payload.is_object())
  174. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  175. auto const& properties = payload.as_object();
  176. auto resolve_property = [](auto name, auto const* property, auto min, auto max) -> ErrorOr<Optional<i32>, Web::WebDriver::Error> {
  177. if (!property)
  178. return Optional<i32> {};
  179. if (!property->is_number())
  180. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' is not a Number", name));
  181. auto number = property->template to_number<i64>();
  182. if (number < min)
  183. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the minimum allowed value {}", name, number, min));
  184. if (number > max)
  185. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the maximum allowed value {}", name, number, max));
  186. return static_cast<i32>(number);
  187. };
  188. // 1. Let width be the result of getting a property named width from the parameters argument, else let it be null.
  189. auto const* width_property = properties.get_ptr("width"sv);
  190. // 2. Let height be the result of getting a property named height from the parameters argument, else let it be null.
  191. auto const* height_property = properties.get_ptr("height"sv);
  192. // 3. Let x be the result of getting a property named x from the parameters argument, else let it be null.
  193. auto const* x_property = properties.get_ptr("x"sv);
  194. // 4. Let y be the result of getting a property named y from the parameters argument, else let it be null.
  195. auto const* y_property = properties.get_ptr("y"sv);
  196. // 5. If width or height is neither null nor a Number from 0 to 2^31 − 1, return error with error code invalid argument.
  197. auto width = TRY(resolve_property("width"sv, width_property, 0, NumericLimits<i32>::max()));
  198. auto height = TRY(resolve_property("height"sv, height_property, 0, NumericLimits<i32>::max()));
  199. // 6. If x or y is neither null nor a Number from −(2^31) to 2^31 − 1, return error with error code invalid argument.
  200. auto x = TRY(resolve_property("x"sv, x_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  201. auto y = TRY(resolve_property("y"sv, y_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  202. // 7. If the remote end does not support the Set Window Rect command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  203. // 8. If the current top-level browsing context is no longer open, return error with error code no such window.
  204. TRY(ensure_open_top_level_browsing_context());
  205. // FIXME: 9. Handle any user prompts and return its value if it is an error.
  206. // FIXME: 10. Fully exit fullscreen.
  207. // 11. Restore the window.
  208. restore_the_window();
  209. Gfx::IntRect window_rect;
  210. // 11. If width and height are not null:
  211. if (width.has_value() && height.has_value()) {
  212. // a. Set the width, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to width.
  213. // b. Set the height, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to height.
  214. auto size = m_web_content_client.did_request_resize_window({ *width, *height });
  215. window_rect.set_size(size);
  216. } else {
  217. window_rect.set_size(m_page_host.page().window_size());
  218. }
  219. // 12. If x and y are not null:
  220. if (x.has_value() && y.has_value()) {
  221. // a. Run the implementation-specific steps to set the position of the operating system level window containing the current top-level browsing context to the position given by the x and y coordinates.
  222. auto position = m_web_content_client.did_request_reposition_window({ *x, *y });
  223. window_rect.set_location(position);
  224. } else {
  225. window_rect.set_location(m_page_host.page().window_position());
  226. }
  227. // 14. Return success with data set to the WindowRect object for the current top-level browsing context.
  228. return serialize_rect(window_rect);
  229. }
  230. // 11.8.3 Maximize Window, https://w3c.github.io/webdriver/#dfn-maximize-window
  231. Messages::WebDriverClient::MaximizeWindowResponse WebDriverConnection::maximize_window()
  232. {
  233. // 1. If the remote end does not support the Maximize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  234. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  235. TRY(ensure_open_top_level_browsing_context());
  236. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  237. // FIXME: 4. Fully exit fullscreen.
  238. // 5. Restore the window.
  239. restore_the_window();
  240. // 6. Maximize the window of the current top-level browsing context.
  241. auto window_rect = maximize_the_window();
  242. // 7. Return success with data set to the WindowRect object for the current top-level browsing context.
  243. return serialize_rect(window_rect);
  244. }
  245. // 11.8.4 Minimize Window, https://w3c.github.io/webdriver/#minimize-window
  246. Messages::WebDriverClient::MinimizeWindowResponse WebDriverConnection::minimize_window()
  247. {
  248. // 1. If the remote end does not support the Minimize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  249. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  250. TRY(ensure_open_top_level_browsing_context());
  251. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  252. // FIXME: 4. Fully exit fullscreen.
  253. // 5. Iconify the window.
  254. auto window_rect = iconify_the_window();
  255. // 6. Return success with data set to the WindowRect object for the current top-level browsing context.
  256. return serialize_rect(window_rect);
  257. }
  258. // 12.3.2 Find Element, https://w3c.github.io/webdriver/#dfn-find-element
  259. Messages::WebDriverClient::FindElementResponse WebDriverConnection::find_element(JsonValue const& payload)
  260. {
  261. // 1. Let location strategy be the result of getting a property called "using".
  262. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  263. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  264. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  265. if (!location_strategy.has_value())
  266. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  267. // 3. Let selector be the result of getting a property called "value".
  268. // 4. If selector is undefined, return error with error code invalid argument.
  269. auto selector = TRY(get_property(payload, "value"sv));
  270. // 5. If the current browsing context is no longer open, return error with error code no such window.
  271. TRY(ensure_open_top_level_browsing_context());
  272. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  273. // 7. Let start node be the current browsing context’s document element.
  274. auto* start_node = m_page_host.page().top_level_browsing_context().active_document();
  275. // 8. If start node is null, return error with error code no such element.
  276. if (!start_node)
  277. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);
  278. // 9. Let result be the result of trying to Find with start node, location strategy, and selector.
  279. auto result = TRY(find(*start_node, *location_strategy, selector));
  280. // 10. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  281. if (result.is_empty())
  282. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);
  283. return make_success_response(result.at(0));
  284. }
  285. // 12.3.3 Find Elements, https://w3c.github.io/webdriver/#dfn-find-elements
  286. Messages::WebDriverClient::FindElementsResponse WebDriverConnection::find_elements(JsonValue const& payload)
  287. {
  288. // 1. Let location strategy be the result of getting a property called "using".
  289. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  290. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  291. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  292. if (!location_strategy.has_value())
  293. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  294. // 3. Let selector be the result of getting a property called "value".
  295. // 4. If selector is undefined, return error with error code invalid argument.
  296. auto selector = TRY(get_property(payload, "value"sv));
  297. // 5. If the current browsing context is no longer open, return error with error code no such window.
  298. TRY(ensure_open_top_level_browsing_context());
  299. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  300. // 7. Let start node be the current browsing context’s document element.
  301. auto* start_node = m_page_host.page().top_level_browsing_context().active_document();
  302. // 8. If start node is null, return error with error code no such element.
  303. if (!start_node)
  304. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);
  305. // 9. Return the result of trying to Find with start node, location strategy, and selector.
  306. auto result = TRY(find(*start_node, *location_strategy, selector));
  307. return make_success_response(move(result));
  308. }
  309. // 12.3.4 Find Element From Element, https://w3c.github.io/webdriver/#dfn-find-element-from-element
  310. Messages::WebDriverClient::FindElementFromElementResponse WebDriverConnection::find_element_from_element(JsonValue const& payload, String const& element_id)
  311. {
  312. // 1. Let location strategy be the result of getting a property called "using".
  313. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  314. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  315. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  316. if (!location_strategy.has_value())
  317. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  318. // 3. Let selector be the result of getting a property called "value".
  319. // 4. If selector is undefined, return error with error code invalid argument.
  320. auto selector = TRY(get_property(payload, "value"sv));
  321. // 5. If the current browsing context is no longer open, return error with error code no such window.
  322. TRY(ensure_open_top_level_browsing_context());
  323. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  324. // 7. Let start node be the result of trying to get a known connected element with url variable element id.
  325. auto* start_node = TRY(get_known_connected_element(element_id));
  326. // 8. Let result be the value of trying to Find with start node, location strategy, and selector.
  327. auto result = TRY(find(*start_node, *location_strategy, selector));
  328. // 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  329. if (result.is_empty())
  330. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);
  331. return make_success_response(result.at(0));
  332. }
  333. // 12.3.5 Find Elements From Element, https://w3c.github.io/webdriver/#dfn-find-elements-from-element
  334. Messages::WebDriverClient::FindElementsFromElementResponse WebDriverConnection::find_elements_from_element(JsonValue const& payload, String const& element_id)
  335. {
  336. // 1. Let location strategy be the result of getting a property called "using".
  337. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  338. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  339. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  340. if (!location_strategy.has_value())
  341. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  342. // 3. Let selector be the result of getting a property called "value".
  343. // 4. If selector is undefined, return error with error code invalid argument.
  344. auto selector = TRY(get_property(payload, "value"sv));
  345. // 5. If the current browsing context is no longer open, return error with error code no such window.
  346. TRY(ensure_open_top_level_browsing_context());
  347. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  348. // 7. Let start node be the result of trying to get a known connected element with url variable element id.
  349. auto* start_node = TRY(get_known_connected_element(element_id));
  350. // 8. Return the result of trying to Find with start node, location strategy, and selector.
  351. auto result = TRY(find(*start_node, *location_strategy, selector));
  352. return make_success_response(move(result));
  353. }
  354. // 12.4.1 Is Element Selected, https://w3c.github.io/webdriver/#dfn-is-element-selected
  355. Messages::WebDriverClient::IsElementSelectedResponse WebDriverConnection::is_element_selected(String const& element_id)
  356. {
  357. // 1. If the current browsing context is no longer open, return error with error code no such window.
  358. TRY(ensure_open_top_level_browsing_context());
  359. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  360. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  361. auto* element = TRY(get_known_connected_element(element_id));
  362. // 4. Let selected be the value corresponding to the first matching statement:
  363. bool selected = false;
  364. // element is an input element with a type attribute in the Checkbox- or Radio Button state
  365. if (is<Web::HTML::HTMLInputElement>(*element)) {
  366. // -> The result of element’s checkedness.
  367. auto& input = static_cast<Web::HTML::HTMLInputElement&>(*element);
  368. using enum Web::HTML::HTMLInputElement::TypeAttributeState;
  369. if (input.type_state() == Checkbox || input.type_state() == RadioButton)
  370. selected = input.checked();
  371. }
  372. // element is an option element
  373. else if (is<Web::HTML::HTMLOptionElement>(*element)) {
  374. // -> The result of element’s selectedness.
  375. selected = static_cast<Web::HTML::HTMLOptionElement&>(*element).selected();
  376. }
  377. // Otherwise
  378. // -> False.
  379. // 5. Return success with data selected.
  380. return make_success_response(selected);
  381. }
  382. // 12.4.2 Get Element Attribute, https://w3c.github.io/webdriver/#dfn-get-element-attribute
  383. Messages::WebDriverClient::GetElementAttributeResponse WebDriverConnection::get_element_attribute(String const& element_id, String const& name)
  384. {
  385. // 1. If the current browsing context is no longer open, return error with error code no such window.
  386. TRY(ensure_open_top_level_browsing_context());
  387. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  388. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  389. auto* element = TRY(get_known_connected_element(element_id));
  390. // 4. Let result be the result of the first matching condition:
  391. Optional<String> result;
  392. // -> If name is a boolean attribute
  393. if (Web::HTML::is_boolean_attribute(name)) {
  394. // "true" (string) if the element has the attribute, otherwise null.
  395. if (element->has_attribute(name))
  396. result = "true"sv;
  397. }
  398. // -> Otherwise
  399. else {
  400. // The result of getting an attribute by name name.
  401. result = element->get_attribute(name);
  402. }
  403. // 5. Return success with data result.
  404. if (result.has_value())
  405. return make_success_response(result.release_value());
  406. return make_success_response({});
  407. }
  408. // 12.4.3 Get Element Property, https://w3c.github.io/webdriver/#dfn-get-element-property
  409. Messages::WebDriverClient::GetElementPropertyResponse WebDriverConnection::get_element_property(String const& element_id, String const& name)
  410. {
  411. // 1. If the current browsing context is no longer open, return error with error code no such window.
  412. TRY(ensure_open_top_level_browsing_context());
  413. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  414. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  415. auto* element = TRY(get_known_connected_element(element_id));
  416. Optional<String> result;
  417. // 4. Let property be the result of calling the Object.[[GetProperty]](name) on element.
  418. if (auto property_or_error = element->get(name); !property_or_error.is_throw_completion()) {
  419. auto property = property_or_error.release_value();
  420. // 5. Let result be the value of property if not undefined, or null.
  421. if (!property.is_undefined()) {
  422. if (auto string_or_error = property.to_string(element->vm()); !string_or_error.is_error())
  423. result = string_or_error.release_value();
  424. }
  425. }
  426. // 6. Return success with data result.
  427. if (result.has_value())
  428. return make_success_response(result.release_value());
  429. return make_success_response({});
  430. }
  431. // https://w3c.github.io/webdriver/#dfn-no-longer-open
  432. ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::ensure_open_top_level_browsing_context()
  433. {
  434. // A browsing context is said to be no longer open if it has been discarded.
  435. if (m_page_host.page().top_level_browsing_context().has_been_discarded())
  436. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found"sv);
  437. return {};
  438. }
  439. // https://w3c.github.io/webdriver/#dfn-restore-the-window
  440. void WebDriverConnection::restore_the_window()
  441. {
  442. // To restore the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to restore or unhide the window to the visible screen.
  443. m_web_content_client.async_did_request_restore_window();
  444. // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the visible state, or until the operation times out.
  445. // FIXME: Implement timeouts.
  446. Web::Platform::EventLoopPlugin::the().spin_until([this]() {
  447. auto state = m_page_host.page().top_level_browsing_context().system_visibility_state();
  448. return state == Web::HTML::VisibilityState::Visible;
  449. });
  450. }
  451. // https://w3c.github.io/webdriver/#dfn-maximize-the-window
  452. Gfx::IntRect WebDriverConnection::maximize_the_window()
  453. {
  454. // To maximize the window, given an operating system level window with an associated top-level browsing context, run the implementation-specific steps to transition the operating system level window into the maximized window state.
  455. auto rect = m_web_content_client.did_request_maximize_window();
  456. // Return when the window has completed the transition, or within an implementation-defined timeout.
  457. return rect;
  458. }
  459. // https://w3c.github.io/webdriver/#dfn-iconify-the-window
  460. Gfx::IntRect WebDriverConnection::iconify_the_window()
  461. {
  462. // To iconify the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to iconify, minimize, or hide the window from the visible screen.
  463. auto rect = m_web_content_client.did_request_minimize_window();
  464. // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the hidden state, or until the operation times out.
  465. // FIXME: Implement timeouts.
  466. Web::Platform::EventLoopPlugin::the().spin_until([this]() {
  467. auto state = m_page_host.page().top_level_browsing_context().system_visibility_state();
  468. return state == Web::HTML::VisibilityState::Hidden;
  469. });
  470. return rect;
  471. }
  472. // https://w3c.github.io/webdriver/#dfn-find
  473. ErrorOr<JsonArray, Web::WebDriver::Error> WebDriverConnection::find(Web::DOM::ParentNode& start_node, Web::WebDriver::LocationStrategy using_, StringView value)
  474. {
  475. // FIXME: 1. Let end time be the current time plus the session implicit wait timeout.
  476. // 2. Let location strategy be equal to using.
  477. auto location_strategy = using_;
  478. // 3. Let selector be equal to value.
  479. auto selector = value;
  480. // 4. Let elements returned be the result of trying to call the relevant element location strategy with arguments start node, and selector.
  481. auto elements = Web::WebDriver::invoke_location_strategy(location_strategy, start_node, selector);
  482. // 5. If a DOMException, SyntaxError, XPathException, or other error occurs during the execution of the element location strategy, return error invalid selector.
  483. if (elements.is_error())
  484. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidSelector, String::formatted("The location strategy could not finish: {}", elements.error().message));
  485. // FIXME: 6. If elements returned is empty and the current time is less than end time return to step 4. Otherwise, continue to the next step.
  486. // 7. Let result be an empty JSON List.
  487. JsonArray result;
  488. result.ensure_capacity(elements.value()->length());
  489. // 8. For each element in elements returned, append the web element reference object for element, to result.
  490. for (size_t i = 0; i < elements.value()->length(); ++i)
  491. result.append(web_element_reference_object(*elements.value()->item(i)));
  492. // 9. Return success with data result.
  493. return result;
  494. }
  495. }