Session.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "Session.h"
  10. #include "BrowserConnection.h"
  11. #include "Client.h"
  12. #include <AK/Base64.h>
  13. #include <AK/NumericLimits.h>
  14. #include <AK/Time.h>
  15. #include <AK/URL.h>
  16. #include <LibCore/LocalServer.h>
  17. #include <LibCore/Stream.h>
  18. #include <LibCore/System.h>
  19. #include <LibGfx/PNGWriter.h>
  20. #include <LibGfx/Point.h>
  21. #include <LibGfx/Rect.h>
  22. #include <LibGfx/Size.h>
  23. #include <LibWeb/Cookie/Cookie.h>
  24. #include <LibWeb/Cookie/ParsedCookie.h>
  25. #include <LibWeb/WebDriver/ExecuteScript.h>
  26. #include <unistd.h>
  27. namespace WebDriver {
  28. Session::Session(unsigned session_id, NonnullRefPtr<Client> client)
  29. : m_client(move(client))
  30. , m_id(session_id)
  31. {
  32. }
  33. Session::~Session()
  34. {
  35. if (m_started) {
  36. auto error = stop();
  37. if (error.is_error()) {
  38. warnln("Failed to stop session {}: {}", m_id, error.error());
  39. }
  40. }
  41. }
  42. ErrorOr<Session::Window*, WebDriverError> Session::current_window()
  43. {
  44. auto window = m_windows.get(m_current_window_handle);
  45. if (!window.has_value())
  46. return WebDriverError::from_code(ErrorCode::NoSuchWindow, "Window not found");
  47. return window.release_value();
  48. }
  49. ErrorOr<void, WebDriverError> Session::check_for_open_top_level_browsing_context_or_return_error()
  50. {
  51. (void)TRY(current_window());
  52. return {};
  53. }
  54. ErrorOr<void> Session::start()
  55. {
  56. auto socket_path = String::formatted("/tmp/browser_webdriver_{}_{}", getpid(), m_id);
  57. dbgln("Listening for WebDriver connection on {}", socket_path);
  58. // FIXME: Use Core::LocalServer
  59. struct sockaddr_un addr;
  60. int listen_socket = TRY(Core::System::socket(AF_UNIX, SOCK_STREAM, 0));
  61. ::memset(&addr, 0, sizeof(struct sockaddr_un));
  62. addr.sun_family = AF_UNIX;
  63. ::strncpy(addr.sun_path, socket_path.characters(), sizeof(addr.sun_path) - 1);
  64. TRY(Core::System::bind(listen_socket, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)));
  65. TRY(Core::System::listen(listen_socket, 1));
  66. char const* argv[] = { "/bin/Browser", "--webdriver", socket_path.characters(), nullptr };
  67. TRY(Core::System::posix_spawn("/bin/Browser"sv, nullptr, nullptr, const_cast<char**>(argv), environ));
  68. int data_socket = TRY(Core::System::accept(listen_socket, nullptr, nullptr));
  69. auto socket = TRY(Core::Stream::LocalSocket::adopt_fd(data_socket));
  70. TRY(socket->set_blocking(true));
  71. m_browser_connection = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BrowserConnection(move(socket), m_client, session_id())));
  72. dbgln("Browser is connected");
  73. m_started = true;
  74. m_windows.set("main", make<Session::Window>("main", true));
  75. m_current_window_handle = "main";
  76. return {};
  77. }
  78. ErrorOr<void> Session::stop()
  79. {
  80. m_browser_connection->async_quit();
  81. return {};
  82. }
  83. // 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
  84. JsonObject Session::get_timeouts()
  85. {
  86. // 1. Let timeouts be the timeouts object for session’s timeouts configuration
  87. auto timeouts = timeouts_object(m_timeouts_configuration);
  88. // 2. Return success with data timeouts.
  89. return timeouts;
  90. }
  91. // 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
  92. ErrorOr<JsonValue, WebDriverError> Session::set_timeouts(JsonValue const& payload)
  93. {
  94. // 1. Let timeouts be the result of trying to JSON deserialize as a timeouts configuration the request’s parameters.
  95. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(payload));
  96. // 2. Make the session timeouts the new timeouts.
  97. m_timeouts_configuration = move(timeouts);
  98. // 3. Return success with data null.
  99. return JsonValue {};
  100. }
  101. // 10.1 Navigate To, https://w3c.github.io/webdriver/#dfn-navigate-to
  102. ErrorOr<JsonValue, WebDriverError> Session::navigate_to(JsonValue const& payload)
  103. {
  104. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  105. TRY(check_for_open_top_level_browsing_context_or_return_error());
  106. // FIXME 2. Handle any user prompts and return its value if it is an error.
  107. // 3. If the url property is missing from the parameters argument or it is not a string, return error with error code invalid argument.
  108. if (!payload.is_object() || !payload.as_object().has_string("url"sv)) {
  109. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload doesn't have a string url");
  110. }
  111. // 4. Let url be the result of getting a property named url from the parameters argument.
  112. URL url(payload.as_object().get_ptr("url"sv)->as_string());
  113. // FIXME: 5. If url is not an absolute URL or an absolute URL with fragment, return error with error code invalid argument. [URL]
  114. // 6. Let url be the result of getting a property named url from the parameters argument.
  115. // Duplicate step?
  116. // 7. Navigate the current top-level browsing context to url.
  117. m_browser_connection->async_set_url(url);
  118. // FIXME: 8. Run the post-navigation checks and return its value if it is an error.
  119. // FIXME: 9. Wait for navigation to complete and return its value if it is an error.
  120. // FIXME: 10. Set the current browsing context to the current top-level browsing context.
  121. // 11. Return success with data null.
  122. return JsonValue();
  123. }
  124. // 10.2 Get Current URL, https://w3c.github.io/webdriver/#dfn-get-current-url
  125. ErrorOr<JsonValue, WebDriverError> Session::get_current_url()
  126. {
  127. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  128. TRY(check_for_open_top_level_browsing_context_or_return_error());
  129. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  130. // 3. Let url be the serialization of the current top-level browsing context’s active document’s document URL.
  131. auto url = m_browser_connection->get_url().to_string();
  132. // 4. Return success with data url.
  133. return JsonValue(url);
  134. }
  135. // 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
  136. ErrorOr<JsonValue, WebDriverError> Session::back()
  137. {
  138. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  139. TRY(check_for_open_top_level_browsing_context_or_return_error());
  140. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  141. // 3. Traverse the history by a delta –1 for the current browsing context.
  142. m_browser_connection->async_back();
  143. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  144. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  145. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  146. // prompts have been handled, return error with error code timeout.
  147. // 6. Return success with data null.
  148. return JsonValue();
  149. }
  150. // 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
  151. ErrorOr<JsonValue, WebDriverError> Session::forward()
  152. {
  153. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  154. TRY(check_for_open_top_level_browsing_context_or_return_error());
  155. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  156. // 3. Traverse the history by a delta 1 for the current browsing context.
  157. m_browser_connection->async_forward();
  158. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  159. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  160. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  161. // prompts have been handled, return error with error code timeout.
  162. // 6. Return success with data null.
  163. return JsonValue();
  164. }
  165. // 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
  166. ErrorOr<JsonValue, WebDriverError> Session::refresh()
  167. {
  168. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  169. TRY(check_for_open_top_level_browsing_context_or_return_error());
  170. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  171. // 3. Initiate an overridden reload of the current top-level browsing context’s active document.
  172. m_browser_connection->async_refresh();
  173. // FIXME: 4. If url is special except for file:
  174. // FIXME: 1. Try to wait for navigation to complete.
  175. // FIXME: 2. Try to run the post-navigation checks.
  176. // FIXME: 5. Set the current browsing context with current top-level browsing context.
  177. // 6. Return success with data null.
  178. return JsonValue();
  179. }
  180. // 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
  181. ErrorOr<JsonValue, WebDriverError> Session::get_title()
  182. {
  183. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  184. TRY(check_for_open_top_level_browsing_context_or_return_error());
  185. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  186. // 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.
  187. // 4. Return success with data title.
  188. return JsonValue(m_browser_connection->get_title());
  189. }
  190. // 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle
  191. ErrorOr<JsonValue, WebDriverError> Session::get_window_handle()
  192. {
  193. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  194. TRY(check_for_open_top_level_browsing_context_or_return_error());
  195. // 2. Return success with data being the window handle associated with the current top-level browsing context.
  196. return m_current_window_handle;
  197. }
  198. // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
  199. ErrorOr<void, Variant<WebDriverError, Error>> Session::close_window()
  200. {
  201. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  202. TRY(check_for_open_top_level_browsing_context_or_return_error());
  203. // 2. Close the current top-level browsing context.
  204. m_windows.remove(m_current_window_handle);
  205. // 3. If there are no more open top-level browsing contexts, then close the session.
  206. if (m_windows.is_empty()) {
  207. auto result = stop();
  208. if (result.is_error()) {
  209. return Variant<WebDriverError, Error>(result.release_error());
  210. }
  211. }
  212. return {};
  213. }
  214. // 11.4 Get Window Handles, https://w3c.github.io/webdriver/#dfn-get-window-handles
  215. ErrorOr<JsonValue, WebDriverError> Session::get_window_handles() const
  216. {
  217. // 1. Let handles be a JSON List.
  218. auto handles = JsonArray {};
  219. // 2. For each top-level browsing context in the remote end, push the associated window handle onto handles.
  220. for (auto const& window_handle : m_windows.keys())
  221. handles.append(window_handle);
  222. // 3. Return success with data handles.
  223. return handles;
  224. }
  225. static JsonObject serialize_rect(Gfx::IntRect const& rect)
  226. {
  227. JsonObject serialized_rect = {};
  228. serialized_rect.set("x", rect.x());
  229. serialized_rect.set("y", rect.y());
  230. serialized_rect.set("width", rect.width());
  231. serialized_rect.set("height", rect.height());
  232. return serialized_rect;
  233. }
  234. // 11.8.1 Get Window Rect, https://w3c.github.io/webdriver/#dfn-get-window-rect
  235. ErrorOr<JsonValue, WebDriverError> Session::get_window_rect()
  236. {
  237. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  238. TRY(check_for_open_top_level_browsing_context_or_return_error());
  239. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  240. // 3. Return success with data set to the WindowRect object for the current top-level browsing context.
  241. return serialize_rect(m_browser_connection->get_window_rect());
  242. }
  243. // 11.8.2 Set Window Rect, https://w3c.github.io/webdriver/#dfn-set-window-rect
  244. ErrorOr<JsonValue, WebDriverError> Session::set_window_rect(JsonValue const& payload)
  245. {
  246. if (!payload.is_object())
  247. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  248. auto const& properties = payload.as_object();
  249. auto resolve_property = [](auto name, auto const* property, auto min, auto max) -> ErrorOr<Optional<i32>, WebDriverError> {
  250. if (!property)
  251. return Optional<i32> {};
  252. if (!property->is_number())
  253. return WebDriverError::from_code(ErrorCode::InvalidArgument, String::formatted("Property '{}' is not a Number", name));
  254. auto number = property->template to_number<i64>();
  255. if (number < min)
  256. return WebDriverError::from_code(ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the minimum allowed value {}", name, number, min));
  257. if (number > max)
  258. return WebDriverError::from_code(ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the maximum allowed value {}", name, number, max));
  259. return static_cast<i32>(number);
  260. };
  261. // 1. Let width be the result of getting a property named width from the parameters argument, else let it be null.
  262. auto const* width_property = properties.get_ptr("width"sv);
  263. // 2. Let height be the result of getting a property named height from the parameters argument, else let it be null.
  264. auto const* height_property = properties.get_ptr("height"sv);
  265. // 3. Let x be the result of getting a property named x from the parameters argument, else let it be null.
  266. auto const* x_property = properties.get_ptr("x"sv);
  267. // 4. Let y be the result of getting a property named y from the parameters argument, else let it be null.
  268. auto const* y_property = properties.get_ptr("y"sv);
  269. // 5. If width or height is neither null nor a Number from 0 to 2^31 − 1, return error with error code invalid argument.
  270. auto width = TRY(resolve_property("width"sv, width_property, 0, NumericLimits<i32>::max()));
  271. auto height = TRY(resolve_property("height"sv, height_property, 0, NumericLimits<i32>::max()));
  272. // 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.
  273. auto x = TRY(resolve_property("x"sv, x_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  274. auto y = TRY(resolve_property("y"sv, y_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  275. // 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.
  276. // 8. If the current top-level browsing context is no longer open, return error with error code no such window.
  277. TRY(check_for_open_top_level_browsing_context_or_return_error());
  278. // FIXME: 9. Handle any user prompts and return its value if it is an error.
  279. // FIXME: 10. Fully exit fullscreen.
  280. // 11. Restore the window.
  281. m_browser_connection->async_restore_window();
  282. // 11. If width and height are not null:
  283. if (width.has_value() && height.has_value()) {
  284. // 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.
  285. // 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.
  286. m_browser_connection->async_set_window_size(Gfx::IntSize { *width, *height });
  287. }
  288. // 12. If x and y are not null:
  289. if (x.has_value() && y.has_value()) {
  290. // 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.
  291. m_browser_connection->async_set_window_position(Gfx::IntPoint { *x, *y });
  292. }
  293. // 14. Return success with data set to the WindowRect object for the current top-level browsing context.
  294. return serialize_rect(m_browser_connection->get_window_rect());
  295. }
  296. // 11.8.3 Maximize Window, https://w3c.github.io/webdriver/#dfn-maximize-window
  297. ErrorOr<JsonValue, WebDriverError> Session::maximize_window()
  298. {
  299. // 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.
  300. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  301. TRY(check_for_open_top_level_browsing_context_or_return_error());
  302. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  303. // FIXME: 4. Fully exit fullscreen.
  304. // 5. Restore the window.
  305. m_browser_connection->async_restore_window();
  306. // 6. Maximize the window of the current top-level browsing context.
  307. m_browser_connection->async_maximize_window();
  308. // 7. Return success with data set to the WindowRect object for the current top-level browsing context.
  309. return serialize_rect(m_browser_connection->get_window_rect());
  310. }
  311. // 11.8.4 Minimize Window, https://w3c.github.io/webdriver/#minimize-window
  312. ErrorOr<JsonValue, WebDriverError> Session::minimize_window()
  313. {
  314. // 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.
  315. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  316. TRY(check_for_open_top_level_browsing_context_or_return_error());
  317. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  318. // FIXME: 4. Fully exit fullscreen.
  319. // 5. Iconify the window.
  320. m_browser_connection->async_minimize_window();
  321. // 6. Return success with data set to the WindowRect object for the current top-level browsing context.
  322. return serialize_rect(m_browser_connection->get_window_rect());
  323. }
  324. // https://w3c.github.io/webdriver/#dfn-get-or-create-a-web-element-reference
  325. static String get_or_create_a_web_element_reference(Session::LocalElement const& element)
  326. {
  327. // FIXME: 1. For each known element of the current browsing context’s list of known elements:
  328. // FIXME: 1. If known element equals element, return success with known element’s web element reference.
  329. // FIXME: 2. Add element to the list of known elements of the current browsing context.
  330. // FIXME: 3. Return success with the element’s web element reference.
  331. return String::formatted("{}", element.id);
  332. }
  333. // https://w3c.github.io/webdriver/#dfn-web-element-identifier
  334. static const String web_element_identifier = "element-6066-11e4-a52e-4f735466cecf";
  335. // https://w3c.github.io/webdriver/#dfn-web-element-reference-object
  336. static JsonObject web_element_reference_object(Session::LocalElement const& element)
  337. {
  338. // 1. Let identifier be the web element identifier.
  339. auto identifier = web_element_identifier;
  340. // 2. Let reference be the result of get or create a web element reference given element.
  341. auto reference = get_or_create_a_web_element_reference(element);
  342. // 3. Return a JSON Object initialized with a property with name identifier and value reference.
  343. JsonObject object;
  344. object.set("name"sv, identifier);
  345. object.set("value"sv, reference);
  346. return object;
  347. }
  348. // https://w3c.github.io/webdriver/#dfn-find
  349. ErrorOr<JsonArray, WebDriverError> Session::find(Session::LocalElement const& start_node, StringView const& using_, StringView const& value)
  350. {
  351. // 1. Let end time be the current time plus the session implicit wait timeout.
  352. auto end_time = Time::now_monotonic() + Time::from_milliseconds(static_cast<i64>(m_timeouts_configuration.implicit_wait_timeout));
  353. // 2. Let location strategy be equal to using.
  354. auto location_strategy = using_;
  355. // 3. Let selector be equal to value.
  356. auto selector = value;
  357. // 4. Let elements returned be the result of trying to call the relevant element location strategy with arguments start node, and selector.
  358. auto location_strategy_handler = s_locator_strategies.first_matching([&](LocatorStrategy const& match) { return match.name == location_strategy; });
  359. if (!location_strategy_handler.has_value())
  360. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No valid location strategy");
  361. auto elements_or_error = (this->*location_strategy_handler.value().handler)(start_node, selector);
  362. // 5. If a DOMException, SyntaxError, XPathException, or other error occurs during the execution of the element location strategy, return error invalid selector.
  363. if (elements_or_error.is_error())
  364. return WebDriverError::from_code(ErrorCode::InvalidSelector, String::formatted("The location strategy could not finish: {}", elements_or_error.release_error().message));
  365. auto elements = elements_or_error.release_value();
  366. // 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.
  367. (void)end_time;
  368. // 7. Let result be an empty JSON List.
  369. auto result = JsonArray();
  370. // 8. For each element in elements returned, append the web element reference object for element, to result.
  371. for (auto const& element : elements) {
  372. result.append(JsonValue(web_element_reference_object(element)));
  373. }
  374. // 9. Return success with data result.
  375. return result;
  376. }
  377. // https://w3c.github.io/webdriver/#dfn-table-of-location-strategies
  378. Vector<Session::LocatorStrategy> Session::s_locator_strategies = {
  379. { "css selector", &Session::locator_strategy_css_selectors },
  380. { "link text", &Session::locator_strategy_link_text },
  381. { "partial link text", &Session::locator_strategy_partial_link_text },
  382. { "tag name", &Session::locator_strategy_tag_name },
  383. { "xpath", &Session::locator_strategy_x_path },
  384. };
  385. // https://w3c.github.io/webdriver/#css-selectors
  386. ErrorOr<Vector<Session::LocalElement>, WebDriverError> Session::locator_strategy_css_selectors(Session::LocalElement const& start_node, StringView const& selector)
  387. {
  388. // 1. Let elements be the result of calling querySelectorAll() with start node as this and selector as the argument.
  389. // If this causes an exception to be thrown, return error with error code invalid selector.
  390. auto elements_ids = m_browser_connection->query_selector_all(start_node.id, selector);
  391. if (!elements_ids.has_value())
  392. return WebDriverError::from_code(ErrorCode::InvalidSelector, "query_selector_all returned failed!");
  393. Vector<Session::LocalElement> elements;
  394. for (auto id : elements_ids.release_value()) {
  395. elements.append({ id });
  396. }
  397. // 2.Return success with data elements.
  398. return elements;
  399. }
  400. // https://w3c.github.io/webdriver/#link-text
  401. ErrorOr<Vector<Session::LocalElement>, WebDriverError> Session::locator_strategy_link_text(Session::LocalElement const&, StringView const&)
  402. {
  403. // FIXME: Implement
  404. return WebDriverError::from_code(ErrorCode::UnsupportedOperation, "Not implemented: locator strategy link text");
  405. }
  406. // https://w3c.github.io/webdriver/#partial-link-text
  407. ErrorOr<Vector<Session::LocalElement>, WebDriverError> Session::locator_strategy_partial_link_text(Session::LocalElement const&, StringView const&)
  408. {
  409. // FIXME: Implement
  410. return WebDriverError::from_code(ErrorCode::UnsupportedOperation, "Not implemented: locator strategy partial link text");
  411. }
  412. // https://w3c.github.io/webdriver/#tag-name
  413. ErrorOr<Vector<Session::LocalElement>, WebDriverError> Session::locator_strategy_tag_name(Session::LocalElement const&, StringView const&)
  414. {
  415. // FIXME: Implement
  416. return WebDriverError::from_code(ErrorCode::UnsupportedOperation, "Not implemented: locator strategy tag name");
  417. }
  418. // https://w3c.github.io/webdriver/#xpath
  419. ErrorOr<Vector<Session::LocalElement>, WebDriverError> Session::locator_strategy_x_path(Session::LocalElement const&, StringView const&)
  420. {
  421. // FIXME: Implement
  422. return WebDriverError::from_code(ErrorCode::UnsupportedOperation, "Not implemented: locator strategy XPath");
  423. }
  424. // 12.3.2 Find Element, https://w3c.github.io/webdriver/#dfn-find-element
  425. ErrorOr<JsonValue, WebDriverError> Session::find_element(JsonValue const& payload)
  426. {
  427. if (!payload.is_object())
  428. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  429. auto const& properties = payload.as_object();
  430. // 1. Let location strategy be the result of getting a property called "using".
  431. if (!properties.has("using"sv))
  432. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'using' present");
  433. auto const& maybe_location_strategy = properties.get("using"sv);
  434. if (!maybe_location_strategy.is_string())
  435. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'using' is not a String");
  436. auto location_strategy = maybe_location_strategy.to_string();
  437. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  438. if (!s_locator_strategies.first_matching([&](LocatorStrategy const& match) { return match.name == location_strategy; }).has_value())
  439. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No valid location strategy");
  440. // 3. Let selector be the result of getting a property called "value".
  441. // 4. If selector is undefined, return error with error code invalid argument.
  442. if (!properties.has("value"sv))
  443. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'value' present");
  444. auto const& maybe_selector = properties.get("value"sv);
  445. if (!maybe_selector.is_string())
  446. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'value' is not a String");
  447. auto selector = maybe_selector.to_string();
  448. // 5. If the current browsing context is no longer open, return error with error code no such window.
  449. TRY(check_for_open_top_level_browsing_context_or_return_error());
  450. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  451. // 7. Let start node be the current browsing context’s document element.
  452. auto maybe_start_node_id = m_browser_connection->get_document_element();
  453. // 8. If start node is null, return error with error code no such element.
  454. if (!maybe_start_node_id.has_value())
  455. return WebDriverError::from_code(ErrorCode::NoSuchElement, "document element does not exist");
  456. auto start_node_id = maybe_start_node_id.release_value();
  457. LocalElement start_node = { start_node_id };
  458. // 9. Let result be the result of trying to Find with start node, location strategy, and selector.
  459. auto result = TRY(find(start_node, location_strategy, selector));
  460. // 10. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  461. if (result.is_empty())
  462. return WebDriverError::from_code(ErrorCode::NoSuchElement, "The requested element does not exist");
  463. return JsonValue(result.at(0));
  464. }
  465. // 12.3.3 Find Elements, https://w3c.github.io/webdriver/#dfn-find-elements
  466. ErrorOr<JsonValue, WebDriverError> Session::find_elements(JsonValue const& payload)
  467. {
  468. if (!payload.is_object())
  469. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  470. auto const& properties = payload.as_object();
  471. // 1. Let location strategy be the result of getting a property called "using".
  472. if (!properties.has("using"sv))
  473. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'using' present");
  474. auto const& maybe_location_strategy = properties.get("using"sv);
  475. if (!maybe_location_strategy.is_string())
  476. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'using' is not a String");
  477. auto location_strategy = maybe_location_strategy.to_string();
  478. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  479. if (!s_locator_strategies.first_matching([&](LocatorStrategy const& match) { return match.name == location_strategy; }).has_value())
  480. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No valid location strategy");
  481. // 3. Let selector be the result of getting a property called "value".
  482. // 4. If selector is undefined, return error with error code invalid argument.
  483. if (!properties.has("value"sv))
  484. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'value' present");
  485. auto const& maybe_selector = properties.get("value"sv);
  486. if (!maybe_selector.is_string())
  487. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'value' is not a String");
  488. auto selector = maybe_selector.to_string();
  489. // 5. If the current browsing context is no longer open, return error with error code no such window.
  490. TRY(check_for_open_top_level_browsing_context_or_return_error());
  491. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  492. // 7. Let start node be the current browsing context’s document element.
  493. auto maybe_start_node_id = m_browser_connection->get_document_element();
  494. // 8. If start node is null, return error with error code no such element.
  495. if (!maybe_start_node_id.has_value())
  496. return WebDriverError::from_code(ErrorCode::NoSuchElement, "document element does not exist");
  497. auto start_node_id = maybe_start_node_id.release_value();
  498. LocalElement start_node = { start_node_id };
  499. // 9. Return the result of trying to Find with start node, location strategy, and selector.
  500. auto result = TRY(find(start_node, location_strategy, selector));
  501. return JsonValue(result);
  502. }
  503. // 12.3.4 Find Element From Element, https://w3c.github.io/webdriver/#dfn-find-element-from-element
  504. ErrorOr<JsonValue, WebDriverError> Session::find_element_from_element(JsonValue const& payload, StringView parameter_element_id)
  505. {
  506. if (!payload.is_object())
  507. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  508. auto const& properties = payload.as_object();
  509. // 1. Let location strategy be the result of getting a property called "using".
  510. if (!properties.has("using"sv))
  511. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'using' present");
  512. auto const& maybe_location_strategy = properties.get("using"sv);
  513. if (!maybe_location_strategy.is_string())
  514. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'using' is not a String");
  515. auto location_strategy = maybe_location_strategy.to_string();
  516. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  517. if (!s_locator_strategies.first_matching([&](LocatorStrategy const& match) { return match.name == location_strategy; }).has_value())
  518. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No valid location strategy");
  519. // 3. Let selector be the result of getting a property called "value".
  520. // 4. If selector is undefined, return error with error code invalid argument.
  521. if (!properties.has("value"sv))
  522. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'value' present");
  523. auto const& maybe_selector = properties.get("value"sv);
  524. if (!maybe_selector.is_string())
  525. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'value' is not a String");
  526. auto selector = maybe_selector.to_string();
  527. // 5. If the current browsing context is no longer open, return error with error code no such window.
  528. TRY(check_for_open_top_level_browsing_context_or_return_error());
  529. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  530. // FIXME: 7. Let start node be the result of trying to get a known connected element with url variable element id.
  531. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  532. // For now the element is only represented by its ID
  533. auto maybe_element_id = parameter_element_id.to_int();
  534. if (!maybe_element_id.has_value())
  535. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  536. auto element_id = maybe_element_id.release_value();
  537. LocalElement start_node = { element_id };
  538. // 8. Let result be the value of trying to Find with start node, location strategy, and selector.
  539. auto result = TRY(find(start_node, location_strategy, selector));
  540. // 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  541. if (result.is_empty())
  542. return WebDriverError::from_code(ErrorCode::NoSuchElement, "The requested element does not exist");
  543. return JsonValue(result.at(0));
  544. }
  545. // 12.3.5 Find Elements From Element, https://w3c.github.io/webdriver/#dfn-find-elements-from-element
  546. ErrorOr<JsonValue, WebDriverError> Session::find_elements_from_element(JsonValue const& payload, StringView parameter_element_id)
  547. {
  548. if (!payload.is_object())
  549. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  550. auto const& properties = payload.as_object();
  551. // 1. Let location strategy be the result of getting a property called "using".
  552. if (!properties.has("using"sv))
  553. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'using' present");
  554. auto const& maybe_location_strategy = properties.get("using"sv);
  555. if (!maybe_location_strategy.is_string())
  556. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'using' is not a String");
  557. auto location_strategy = maybe_location_strategy.to_string();
  558. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  559. if (!s_locator_strategies.first_matching([&](LocatorStrategy const& match) { return match.name == location_strategy; }).has_value())
  560. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No valid location strategy");
  561. // 3. Let selector be the result of getting a property called "value".
  562. // 4. If selector is undefined, return error with error code invalid argument.
  563. if (!properties.has("value"sv))
  564. return WebDriverError::from_code(ErrorCode::InvalidArgument, "No property called 'value' present");
  565. auto const& maybe_selector = properties.get("value"sv);
  566. if (!maybe_selector.is_string())
  567. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Property 'value' is not a String");
  568. auto selector = maybe_selector.to_string();
  569. // 5. If the current browsing context is no longer open, return error with error code no such window.
  570. TRY(check_for_open_top_level_browsing_context_or_return_error());
  571. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  572. // FIXME: 7. Let start node be the result of trying to get a known connected element with url variable element id.
  573. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  574. // For now the element is only represented by its ID
  575. auto maybe_element_id = parameter_element_id.to_int();
  576. if (!maybe_element_id.has_value())
  577. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  578. auto element_id = maybe_element_id.release_value();
  579. LocalElement start_node = { element_id };
  580. // 8. Return the result of trying to Find with start node, location strategy, and selector.
  581. auto result = TRY(find(start_node, location_strategy, selector));
  582. return JsonValue(result);
  583. }
  584. // 12.4.2 Get Element Attribute, https://w3c.github.io/webdriver/#dfn-get-element-attribute
  585. ErrorOr<JsonValue, WebDriverError> Session::get_element_attribute(JsonValue const&, StringView parameter_element_id, StringView name)
  586. {
  587. // 1. If the current browsing context is no longer open, return error with error code no such window.
  588. TRY(check_for_open_top_level_browsing_context_or_return_error());
  589. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  590. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  591. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  592. // For now the element is only represented by its ID
  593. auto maybe_element_id = parameter_element_id.to_int();
  594. if (!maybe_element_id.has_value())
  595. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  596. auto element_id = maybe_element_id.release_value();
  597. // FIXME: The case that the element does not exist is not handled at all and null is returned in that case.
  598. // 4. Let result be the result of the first matching condition:
  599. // -> FIXME: If name is a boolean attribute
  600. // NOTE: LibWeb doesn't know about boolean attributes directly
  601. // "true" (string) if the element has the attribute, otherwise null.
  602. // -> Otherwise
  603. // The result of getting an attribute by name name.
  604. auto result = m_browser_connection->get_element_attribute(element_id, name);
  605. if (!result.has_value())
  606. return JsonValue(AK::JsonValue::Type::Null);
  607. // 5. Return success with data result.
  608. return JsonValue(result.release_value());
  609. }
  610. // 12.4.3 Get Element Property, https://w3c.github.io/webdriver/#dfn-get-element-property
  611. ErrorOr<JsonValue, WebDriverError> Session::get_element_property(JsonValue const&, StringView parameter_element_id, StringView name)
  612. {
  613. // 1. If the current browsing context is no longer open, return error with error code no such window.
  614. TRY(check_for_open_top_level_browsing_context_or_return_error());
  615. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  616. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  617. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  618. // For now the element is only represented by its ID
  619. auto maybe_element_id = parameter_element_id.to_int();
  620. if (!maybe_element_id.has_value())
  621. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  622. auto element_id = maybe_element_id.release_value();
  623. // 4. Let property be the result of calling the Object.[[GetProperty]](name) on element.
  624. auto property = m_browser_connection->get_element_property(element_id, name);
  625. // 5. Let result be the value of property if not undefined, or null.
  626. if (!property.has_value())
  627. return JsonValue();
  628. // 6. Return success with data result.
  629. return JsonValue(property.release_value());
  630. }
  631. // 12.4.4 Get Element CSS Value, https://w3c.github.io/webdriver/#dfn-get-element-css-value
  632. ErrorOr<JsonValue, WebDriverError> Session::get_element_css_value(JsonValue const&, StringView parameter_element_id, StringView property_name)
  633. {
  634. // 1. If the current browsing context is no longer open, return error with error code no such window.
  635. TRY(check_for_open_top_level_browsing_context_or_return_error());
  636. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  637. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  638. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  639. // For now the element is only represented by its ID
  640. auto maybe_element_id = parameter_element_id.to_int();
  641. if (!maybe_element_id.has_value())
  642. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  643. auto element_id = maybe_element_id.release_value();
  644. // 4. Let computed value be the result of the first matching condition:
  645. // -> current browsing context’s active document’s type is not "xml"
  646. // computed value of parameter property name from element’s style declarations. property name is obtained from url variables.
  647. // -> Otherwise
  648. // "" (empty string)
  649. auto active_documents_type = m_browser_connection->get_active_documents_type();
  650. if (active_documents_type == "xml")
  651. return JsonValue("");
  652. auto computed_value = m_browser_connection->get_computed_value_for_element(element_id, property_name);
  653. // 5. Return success with data computed value.
  654. return JsonValue(computed_value);
  655. }
  656. // 12.4.5 Get Element Text, https://w3c.github.io/webdriver/#dfn-get-element-text
  657. ErrorOr<JsonValue, WebDriverError> Session::get_element_text(JsonValue const&, StringView parameter_element_id)
  658. {
  659. // 1. If the current browsing context is no longer open, return error with error code no such window.
  660. TRY(check_for_open_top_level_browsing_context_or_return_error());
  661. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  662. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  663. auto maybe_element_id = parameter_element_id.to_int();
  664. if (!maybe_element_id.has_value())
  665. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  666. auto element_id = maybe_element_id.release_value();
  667. // 4. Let rendered text be the result of performing implementation-specific steps whose result is exactly the
  668. // same as the result of a Function.[[Call]](null, element) with bot.dom.getVisibleText as the this value.
  669. auto rendered_text = m_browser_connection->get_element_text(element_id);
  670. // 5. Return success with data rendered text.
  671. return JsonValue(rendered_text);
  672. }
  673. // 12.4.6 Get Element Tag Name, https://w3c.github.io/webdriver/#dfn-get-element-tag-name
  674. ErrorOr<JsonValue, WebDriverError> Session::get_element_tag_name(JsonValue const&, StringView parameter_element_id)
  675. {
  676. // 1. If the current browsing context is no longer open, return error with error code no such window.
  677. TRY(check_for_open_top_level_browsing_context_or_return_error());
  678. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  679. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  680. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference()
  681. // For now the element is only represented by its ID
  682. auto maybe_element_id = parameter_element_id.to_int();
  683. if (!maybe_element_id.has_value())
  684. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Element ID is not an i32");
  685. auto element_id = maybe_element_id.release_value();
  686. // 4. Let qualified name be the result of getting element’s tagName IDL attribute.
  687. auto qualified_name = m_browser_connection->get_element_tag_name(element_id);
  688. // 5. Return success with data qualified name.
  689. return JsonValue(qualified_name);
  690. }
  691. // 13.1 Get Page Source, https://w3c.github.io/webdriver/#dfn-get-page-source
  692. ErrorOr<JsonValue, WebDriverError> Session::get_source()
  693. {
  694. // 1. If the current browsing context is no longer open, return error with error code no such window.
  695. TRY(check_for_open_top_level_browsing_context_or_return_error());
  696. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  697. // 3. Let source be the result of invoking the fragment serializing algorithm on a fictional node whose only child is the document element providing true for the require well-formed flag. If this causes an exception to be thrown, let source be null.
  698. // 4. Let source be the result of serializing to string the current browsing context active document, if source is null.
  699. // NOTE: Both of the above cases are handled in the remote WebContent process.
  700. auto source = m_browser_connection->serialize_source();
  701. // 5. Return success with data source.
  702. return source;
  703. }
  704. struct ScriptArguments {
  705. String script;
  706. JsonArray const& arguments;
  707. };
  708. // https://w3c.github.io/webdriver/#dfn-extract-the-script-arguments-from-a-request
  709. static ErrorOr<ScriptArguments, WebDriverError> extract_the_script_arguments_from_a_request(JsonValue const& payload)
  710. {
  711. if (!payload.is_object())
  712. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  713. auto const& properties = payload.as_object();
  714. // 1. Let script be the result of getting a property named script from the parameters.
  715. // 2. If script is not a String, return error with error code invalid argument.
  716. if (!properties.has_string("script"sv))
  717. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload doesn't have a 'script' string property");
  718. auto script = properties.get("script"sv).as_string();
  719. // 3. Let args be the result of getting a property named args from the parameters.
  720. // 4. If args is not an Array return error with error code invalid argument.
  721. if (!properties.has_array("args"sv))
  722. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload doesn't have an 'args' string property");
  723. auto const& args = properties.get("args"sv).as_array();
  724. // 5. Let arguments be the result of calling the JSON deserialize algorithm with arguments args.
  725. // NOTE: We forward the JSON array to the Browser and then WebContent process over IPC, so this is not necessary.
  726. // 6. Return success with data script and arguments.
  727. return ScriptArguments { script, args };
  728. }
  729. // 13.2.1 Execute Script, https://w3c.github.io/webdriver/#dfn-execute-script
  730. ErrorOr<JsonValue, WebDriverError> Session::execute_script(JsonValue const& payload)
  731. {
  732. // 1. Let body and arguments be the result of trying to extract the script arguments from a request with argument parameters.
  733. auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));
  734. // 2. If the current browsing context is no longer open, return error with error code no such window.
  735. TRY(check_for_open_top_level_browsing_context_or_return_error());
  736. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  737. // 4., 5.1-5.3.
  738. Vector<String> json_arguments;
  739. arguments.for_each([&](JsonValue const& json_value) {
  740. // NOTE: serialized() instead of to_string() ensures proper quoting.
  741. json_arguments.append(json_value.serialized<StringBuilder>());
  742. });
  743. dbgln("Executing script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  744. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, false);
  745. dbgln("Executing script returned: {}", execute_script_response.json_result());
  746. // NOTE: This is assumed to be a valid JSON value.
  747. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  748. switch (execute_script_response.result_type()) {
  749. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  750. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  751. return WebDriverError::from_code(ErrorCode::ScriptTimeoutError, "Script timed out");
  752. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  753. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  754. return result;
  755. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  756. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  757. case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
  758. return WebDriverError::from_code(ErrorCode::JavascriptError, "Script returned an error", move(result));
  759. default:
  760. VERIFY_NOT_REACHED();
  761. }
  762. }
  763. // 13.2.2 Execute Async Script, https://w3c.github.io/webdriver/#dfn-execute-async-script
  764. ErrorOr<JsonValue, WebDriverError> Session::execute_async_script(JsonValue const& parameters)
  765. {
  766. // 1. Let body and arguments by the result of trying to extract the script arguments from a request with argument parameters.
  767. auto [body, arguments] = TRY(extract_the_script_arguments_from_a_request(parameters));
  768. // 2. If the current browsing context is no longer open, return error with error code no such window.
  769. TRY(check_for_open_top_level_browsing_context_or_return_error());
  770. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  771. // 4., 5.1-5.11.
  772. Vector<String> json_arguments;
  773. arguments.for_each([&](JsonValue const& json_value) {
  774. // NOTE: serialized() instead of to_string() ensures proper quoting.
  775. json_arguments.append(json_value.serialized<StringBuilder>());
  776. });
  777. dbgln("Executing async script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  778. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, true);
  779. dbgln("Executing async script returned: {}", execute_script_response.json_result());
  780. // NOTE: This is assumed to be a valid JSON value.
  781. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  782. switch (execute_script_response.result_type()) {
  783. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  784. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  785. return WebDriverError::from_code(ErrorCode::ScriptTimeoutError, "Script timed out");
  786. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  787. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  788. return result;
  789. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  790. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  791. return WebDriverError::from_code(ErrorCode::JavascriptError, "Script returned an error", move(result));
  792. default:
  793. VERIFY_NOT_REACHED();
  794. }
  795. }
  796. // https://w3c.github.io/webdriver/#dfn-serialized-cookie
  797. static JsonObject serialize_cookie(Web::Cookie::Cookie const& cookie)
  798. {
  799. JsonObject serialized_cookie = {};
  800. serialized_cookie.set("name", cookie.name);
  801. serialized_cookie.set("value", cookie.value);
  802. serialized_cookie.set("path", cookie.path);
  803. serialized_cookie.set("domain", cookie.domain);
  804. serialized_cookie.set("secure", cookie.secure);
  805. serialized_cookie.set("httpOnly", cookie.http_only);
  806. serialized_cookie.set("expiry", cookie.expiry_time.timestamp());
  807. // FIXME: Add sameSite to Cookie and serialize it here too.
  808. return serialized_cookie;
  809. }
  810. // 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
  811. ErrorOr<JsonValue, WebDriverError> Session::get_all_cookies()
  812. {
  813. // 1. If the current browsing context is no longer open, return error with error code no such window.
  814. TRY(check_for_open_top_level_browsing_context_or_return_error());
  815. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  816. // 3. Let cookies be a new JSON List.
  817. JsonArray cookies = {};
  818. // 4. For each cookie in all associated cookies of the current browsing context’s active document:
  819. for (auto const& cookie : m_browser_connection->get_all_cookies()) {
  820. // 1. Let serialized cookie be the result of serializing cookie.
  821. auto serialized_cookie = serialize_cookie(cookie);
  822. // 2. Append serialized cookie to cookies
  823. cookies.append(serialized_cookie);
  824. }
  825. // 5. Return success with data cookies.
  826. return JsonValue(cookies);
  827. }
  828. // 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
  829. ErrorOr<JsonValue, WebDriverError> Session::get_named_cookie(String const& name)
  830. {
  831. // 1. If the current browsing context is no longer open, return error with error code no such window.
  832. TRY(check_for_open_top_level_browsing_context_or_return_error());
  833. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  834. // 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the
  835. // current browsing context’s active document, return success with the serialized cookie as data.
  836. auto maybe_cookie = m_browser_connection->get_named_cookie(name);
  837. if (maybe_cookie.has_value()) {
  838. auto cookie = maybe_cookie.release_value();
  839. auto serialized_cookie = serialize_cookie(cookie);
  840. return JsonValue(serialized_cookie);
  841. }
  842. // 4. Otherwise, return error with error code no such cookie.
  843. return WebDriverError::from_code(ErrorCode::NoSuchCookie, "Cookie not found");
  844. }
  845. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  846. ErrorOr<JsonValue, WebDriverError> Session::add_cookie(JsonValue const& payload)
  847. {
  848. // 1. Let data be the result of getting a property named cookie from the parameters argument.
  849. if (!payload.is_object() || !payload.as_object().has_object("cookie"sv))
  850. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Payload doesn't have a cookie object");
  851. auto const& maybe_data = payload.as_object().get("cookie"sv);
  852. // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion,
  853. // return error with error code invalid argument.
  854. // NOTE: Table is here: https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion
  855. if (!maybe_data.is_object())
  856. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Value \"cookie\' is not an object");
  857. auto const& data = maybe_data.as_object();
  858. if (!data.has("name"sv) || !data.has("value"sv))
  859. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Cookie-Object doesn't contain all required keys");
  860. // 3. If the current browsing context is no longer open, return error with error code no such window.
  861. TRY(check_for_open_top_level_browsing_context_or_return_error());
  862. // FIXME: 4. Handle any user prompts, and return its value if it is an error.
  863. // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object,
  864. // return error with error code invalid cookie domain.
  865. // 6. If cookie name or cookie value is null,
  866. // FIXME: cookie domain is not equal to the current browsing context’s active document’s domain,
  867. // cookie secure only or cookie HTTP only are not boolean types,
  868. // or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer,
  869. // return error with error code invalid argument.
  870. if (data.get("name"sv).is_null() || data.get("value"sv).is_null())
  871. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Cookie-Object is malformed: name or value are null");
  872. if (data.has("secure"sv) && !data.get("secure"sv).is_bool())
  873. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Cookie-Object is malformed: secure is not bool");
  874. if (data.has("httpOnly"sv) && !data.get("httpOnly"sv).is_bool())
  875. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Cookie-Object is malformed: httpOnly is not bool");
  876. Optional<Core::DateTime> expiry_time;
  877. if (data.has("expiry"sv)) {
  878. auto expiry_argument = data.get("expiry"sv);
  879. if (!expiry_argument.is_u32()) {
  880. // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
  881. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Cookie-Object is malformed: expiry is not u32");
  882. }
  883. expiry_time = Core::DateTime::from_timestamp(expiry_argument.as_u32());
  884. }
  885. // 7. Create a cookie in the cookie store associated with the active document’s address using
  886. // cookie name name, cookie value value, and an attribute-value list of the following cookie concepts
  887. // listed in the table for cookie conversion from data:
  888. Web::Cookie::ParsedCookie cookie;
  889. if (auto name_attribute = data.get("name"sv); name_attribute.is_string())
  890. cookie.name = name_attribute.as_string();
  891. else
  892. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Expect name attribute to be string");
  893. if (auto value_attribute = data.get("value"sv); value_attribute.is_string())
  894. cookie.value = value_attribute.as_string();
  895. else
  896. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Expect value attribute to be string");
  897. // Cookie path
  898. // The value if the entry exists, otherwise "/".
  899. if (data.has("path"sv)) {
  900. if (auto path_attribute = data.get("path"sv); path_attribute.is_string())
  901. cookie.path = path_attribute.as_string();
  902. else
  903. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Expect path attribute to be string");
  904. } else {
  905. cookie.path = "/";
  906. }
  907. // Cookie domain
  908. // The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
  909. // NOTE: The otherwise case is handled by the CookieJar
  910. if (data.has("domain"sv)) {
  911. if (auto domain_attribute = data.get("domain"sv); domain_attribute.is_string())
  912. cookie.domain = domain_attribute.as_string();
  913. else
  914. return WebDriverError::from_code(ErrorCode::InvalidArgument, "Expect domain attribute to be string");
  915. }
  916. // Cookie secure only
  917. // The value if the entry exists, otherwise false.
  918. if (data.has("secure"sv)) {
  919. cookie.secure_attribute_present = data.get("secure"sv).as_bool();
  920. } else {
  921. cookie.secure_attribute_present = false;
  922. }
  923. // Cookie HTTP only
  924. // The value if the entry exists, otherwise false.
  925. if (data.has("httpOnly"sv)) {
  926. cookie.http_only_attribute_present = data.get("httpOnly"sv).as_bool();
  927. } else {
  928. cookie.http_only_attribute_present = false;
  929. }
  930. // Cookie expiry time
  931. // The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
  932. cookie.expiry_time_from_expires_attribute = expiry_time;
  933. // FIXME: Cookie same site
  934. // The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
  935. m_browser_connection->async_add_cookie(move(cookie));
  936. // If there is an error during this step, return error with error code unable to set cookie.
  937. // NOTE: This probably should only apply to the actual setting of the cookie in the Browser,
  938. // which cannot fail in our case.
  939. // Thus, the error-codes used above are 400 "invalid argument".
  940. // 8. Return success with data null.
  941. return JsonValue();
  942. }
  943. // https://w3c.github.io/webdriver/#dfn-delete-cookies
  944. void Session::delete_cookies(Optional<StringView> const& name)
  945. {
  946. // For each cookie among all associated cookies of the current browsing context’s active document,
  947. // run the substeps of the first matching condition:
  948. for (auto& cookie : m_browser_connection->get_all_cookies()) {
  949. // -> name is undefined
  950. // -> name is equal to cookie name
  951. if (!name.has_value() || name.value() == cookie.name) {
  952. // Set the cookie expiry time to a Unix timestamp in the past.
  953. cookie.expiry_time = Core::DateTime::from_timestamp(0);
  954. m_browser_connection->async_update_cookie(cookie);
  955. }
  956. // -> Otherwise
  957. // Do nothing.
  958. }
  959. }
  960. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  961. ErrorOr<JsonValue, WebDriverError> Session::delete_cookie(StringView const& name)
  962. {
  963. // 1. If the current browsing context is no longer open, return error with error code no such window.
  964. TRY(check_for_open_top_level_browsing_context_or_return_error());
  965. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  966. // 3. Delete cookies using the url variable name parameter as the filter argument.
  967. delete_cookies(name);
  968. // 4. Return success with data null.
  969. return JsonValue();
  970. }
  971. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  972. ErrorOr<JsonValue, WebDriverError> Session::delete_all_cookies()
  973. {
  974. // 1. If the current browsing context is no longer open, return error with error code no such window.
  975. TRY(check_for_open_top_level_browsing_context_or_return_error());
  976. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  977. // 3. Delete cookies, giving no filtering argument.
  978. delete_cookies();
  979. // 4. Return success with data null.
  980. return JsonValue();
  981. }
  982. // https://w3c.github.io/webdriver/#dfn-encoding-a-canvas-as-base64
  983. static ErrorOr<String, WebDriverError> encode_bitmap_as_canvas_element(Gfx::Bitmap const& bitmap)
  984. {
  985. // FIXME: 1. If the canvas element’s bitmap’s origin-clean flag is set to false, return error with error code unable to capture screen.
  986. // 2. If the canvas element’s bitmap has no pixels (i.e. either its horizontal dimension or vertical dimension is zero) then return error with error code unable to capture screen.
  987. if (bitmap.width() == 0 || bitmap.height() == 0)
  988. return WebDriverError::from_code(ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);
  989. // 3. Let file be a serialization of the canvas element’s bitmap as a file, using "image/png" as an argument.
  990. auto file = Gfx::PNGWriter::encode(bitmap);
  991. // 4. Let data url be a data: URL representing file. [RFC2397]
  992. auto data_url = AK::URL::create_with_data("image/png"sv, encode_base64(file), true).to_string();
  993. // 5. Let index be the index of "," in data url.
  994. auto index = data_url.find(',');
  995. VERIFY(index.has_value());
  996. // 6. Let encoded string be a substring of data url using (index + 1) as the start argument.
  997. auto encoded_string = data_url.substring(*index + 1);
  998. // 7. Return success with data encoded string.
  999. return encoded_string;
  1000. }
  1001. // 17.1 Take Screenshot, https://w3c.github.io/webdriver/#take-screenshot
  1002. ErrorOr<JsonValue, WebDriverError> Session::take_screenshot()
  1003. {
  1004. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  1005. TRY(check_for_open_top_level_browsing_context_or_return_error());
  1006. // 2. When the user agent is next to run the animation frame callbacks:
  1007. // a. Let root rect be the current top-level browsing context’s document element’s rectangle.
  1008. // b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given root rect as an argument.
  1009. auto screenshot = m_browser_connection->take_screenshot();
  1010. if (!screenshot.is_valid())
  1011. return WebDriverError::from_code(ErrorCode::UnableToCaptureScreen, "Unable to capture screenshot"sv);
  1012. // c. Let canvas be a canvas element of screenshot result’s data.
  1013. // d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
  1014. // e. Let encoded string be encoding result’s data.
  1015. auto encoded_string = TRY(encode_bitmap_as_canvas_element(*screenshot.bitmap()));
  1016. // 3. Return success with data encoded string.
  1017. return encoded_string;
  1018. }
  1019. }