Window.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/GenericLexer.h>
  10. #include <AK/Utf8View.h>
  11. #include <LibIPC/File.h>
  12. #include <LibJS/Runtime/AbstractOperations.h>
  13. #include <LibJS/Runtime/Accessor.h>
  14. #include <LibJS/Runtime/Completion.h>
  15. #include <LibJS/Runtime/Error.h>
  16. #include <LibJS/Runtime/FunctionObject.h>
  17. #include <LibJS/Runtime/GlobalEnvironment.h>
  18. #include <LibJS/Runtime/NativeFunction.h>
  19. #include <LibJS/Runtime/Shape.h>
  20. #include <LibTextCodec/Decoder.h>
  21. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  22. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  23. #include <LibWeb/Bindings/WindowPrototype.h>
  24. #include <LibWeb/CSS/MediaQueryList.h>
  25. #include <LibWeb/CSS/Parser/Parser.h>
  26. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  27. #include <LibWeb/CSS/Screen.h>
  28. #include <LibWeb/Crypto/Crypto.h>
  29. #include <LibWeb/DOM/Document.h>
  30. #include <LibWeb/DOM/Element.h>
  31. #include <LibWeb/DOM/Event.h>
  32. #include <LibWeb/DOM/EventDispatcher.h>
  33. #include <LibWeb/DOM/HTMLCollection.h>
  34. #include <LibWeb/HTML/BrowsingContext.h>
  35. #include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
  36. #include <LibWeb/HTML/DocumentState.h>
  37. #include <LibWeb/HTML/EventHandler.h>
  38. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  39. #include <LibWeb/HTML/Focus.h>
  40. #include <LibWeb/HTML/HTMLEmbedElement.h>
  41. #include <LibWeb/HTML/HTMLFormElement.h>
  42. #include <LibWeb/HTML/HTMLImageElement.h>
  43. #include <LibWeb/HTML/HTMLObjectElement.h>
  44. #include <LibWeb/HTML/Location.h>
  45. #include <LibWeb/HTML/MessageEvent.h>
  46. #include <LibWeb/HTML/Navigation.h>
  47. #include <LibWeb/HTML/Navigator.h>
  48. #include <LibWeb/HTML/Origin.h>
  49. #include <LibWeb/HTML/PageTransitionEvent.h>
  50. #include <LibWeb/HTML/Parser/HTMLParser.h>
  51. #include <LibWeb/HTML/Scripting/Environments.h>
  52. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  53. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  54. #include <LibWeb/HTML/Storage.h>
  55. #include <LibWeb/HTML/TokenizedFeatures.h>
  56. #include <LibWeb/HTML/TraversableNavigable.h>
  57. #include <LibWeb/HTML/Window.h>
  58. #include <LibWeb/HTML/WindowProxy.h>
  59. #include <LibWeb/HighResolutionTime/Performance.h>
  60. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  61. #include <LibWeb/Infra/Base64.h>
  62. #include <LibWeb/Infra/CharacterTypes.h>
  63. #include <LibWeb/Internals/Inspector.h>
  64. #include <LibWeb/Internals/Internals.h>
  65. #include <LibWeb/Layout/Viewport.h>
  66. #include <LibWeb/Page/Page.h>
  67. #include <LibWeb/Painting/PaintableBox.h>
  68. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  69. #include <LibWeb/Selection/Selection.h>
  70. #include <LibWeb/URL/URL.h>
  71. #include <LibWeb/WebIDL/AbstractOperations.h>
  72. namespace Web::HTML {
  73. JS_DEFINE_ALLOCATOR(Window);
  74. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  75. void run_animation_frame_callbacks(DOM::Document& document, double now)
  76. {
  77. // FIXME: Bring this closer to the spec.
  78. document.window().animation_frame_callback_driver().run(now);
  79. }
  80. class IdleCallback : public RefCounted<IdleCallback> {
  81. public:
  82. explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  83. : m_handler(move(handler))
  84. , m_handle(handle)
  85. {
  86. }
  87. ~IdleCallback() = default;
  88. JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  89. u32 handle() const { return m_handle; }
  90. private:
  91. Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  92. u32 m_handle { 0 };
  93. };
  94. JS::NonnullGCPtr<Window> Window::create(JS::Realm& realm)
  95. {
  96. return realm.heap().allocate<Window>(realm, realm);
  97. }
  98. Window::Window(JS::Realm& realm)
  99. : DOM::EventTarget(realm)
  100. {
  101. m_legacy_platform_object_flags = LegacyPlatformObjectFlags {
  102. .supports_named_properties = true,
  103. .has_legacy_unenumerable_named_properties_interface_extended_attribute = true,
  104. .has_global_interface_extended_attribute = true,
  105. };
  106. }
  107. void Window::visit_edges(JS::Cell::Visitor& visitor)
  108. {
  109. Base::visit_edges(visitor);
  110. WindowOrWorkerGlobalScopeMixin::visit_edges(visitor);
  111. visitor.visit(m_associated_document);
  112. visitor.visit(m_current_event);
  113. visitor.visit(m_performance);
  114. visitor.visit(m_screen);
  115. visitor.visit(m_location);
  116. visitor.visit(m_crypto);
  117. visitor.visit(m_navigator);
  118. visitor.visit(m_navigation);
  119. visitor.visit(m_custom_element_registry);
  120. for (auto& plugin_object : m_pdf_viewer_plugin_objects)
  121. visitor.visit(plugin_object);
  122. for (auto& mime_type_object : m_pdf_viewer_mime_type_objects)
  123. visitor.visit(mime_type_object);
  124. visitor.visit(m_count_queuing_strategy_size_function);
  125. visitor.visit(m_byte_length_queuing_strategy_size_function);
  126. }
  127. void Window::finalize()
  128. {
  129. Base::finalize();
  130. WindowOrWorkerGlobalScopeMixin::finalize();
  131. }
  132. Window::~Window() = default;
  133. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#normalizing-the-feature-name
  134. static String normalize_feature_name(String const& name)
  135. {
  136. // For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
  137. // "screenx"
  138. if (name == "screenx"sv) {
  139. // Return "left".
  140. return "left"_string;
  141. }
  142. // "screeny"
  143. else if (name == "screeny"sv) {
  144. // Return "top".
  145. return "top"_string;
  146. }
  147. // "innerwidth"
  148. else if (name == "innerwidth"sv) {
  149. // Return "width".
  150. return "width"_string;
  151. }
  152. // "innerheight"
  153. else if (name == "innerheight") {
  154. // Return "height".
  155. return "height"_string;
  156. }
  157. // Anything else
  158. else {
  159. // Return name.
  160. return name;
  161. }
  162. }
  163. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-tokenize
  164. static OrderedHashMap<String, String> tokenize_open_features(StringView features)
  165. {
  166. // 1. Let tokenizedFeatures be a new ordered map.
  167. OrderedHashMap<String, String> tokenized_features;
  168. // 2. Let position point at the first code point of features.
  169. GenericLexer lexer(features);
  170. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#feature-separator
  171. auto is_feature_separator = [](auto character) {
  172. return Infra::is_ascii_whitespace(character) || character == '=' || character == ',';
  173. };
  174. // 3. While position is not past the end of features:
  175. while (!lexer.is_eof()) {
  176. // 1. Let name be the empty string.
  177. String name;
  178. // 2. Let value be the empty string.
  179. String value;
  180. // 3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
  181. lexer.ignore_while(is_feature_separator);
  182. // 4. Collect a sequence of code points that are not feature separators from features given position. Set name to the collected characters, converted to ASCII lowercase.
  183. name = MUST(String::from_byte_string(lexer.consume_until(is_feature_separator).to_lowercase_string()));
  184. // 5. Set name to the result of normalizing the feature name name.
  185. name = normalize_feature_name(name);
  186. // 6. While position is not past the end of features and the code point at position in features is not U+003D (=):
  187. // 1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
  188. // 2. Advance position by 1.
  189. lexer.ignore_while(Infra::is_ascii_whitespace);
  190. // 7. If the code point at position in features is a feature separator:
  191. // 1. While position is not past the end of features and the code point at position in features is a feature separator:
  192. // 1. If the code point at position in features is U+002C (,), then break.
  193. // 2. Advance position by 1.
  194. lexer.ignore_while([](auto character) { return Infra::is_ascii_whitespace(character) || character == '='; });
  195. // 2. Collect a sequence of code points that are not feature separators code points from features given position. Set value to the collected code points, converted to ASCII lowercase.
  196. value = MUST(String::from_byte_string(lexer.consume_until(is_feature_separator).to_lowercase_string()));
  197. // 8. If name is not the empty string, then set tokenizedFeatures[name] to value.
  198. if (!name.is_empty())
  199. tokenized_features.set(move(name), move(value));
  200. }
  201. // 4. Return tokenizedFeatures.
  202. return tokenized_features;
  203. }
  204. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-parse-boolean
  205. template<Enum T>
  206. static T parse_boolean_feature(StringView value)
  207. {
  208. // 1. If value is the empty string, then return true.
  209. if (value.is_empty())
  210. return T::Yes;
  211. // 2. If value is "yes", then return true.
  212. if (value == "yes"sv)
  213. return T::Yes;
  214. // 3. If value is "true", then return true.
  215. if (value == "true"sv)
  216. return T::Yes;
  217. // 4. Let parsed be the result of parsing value as an integer.
  218. auto parsed = value.to_number<i64>();
  219. // 5. If parsed is an error, then set it to 0.
  220. if (!parsed.has_value())
  221. parsed = 0;
  222. // 6. Return false if parsed is 0, and true otherwise.
  223. return parsed == 0 ? T::No : T::Yes;
  224. }
  225. // https://html.spec.whatwg.org/multipage/window-object.html#popup-window-is-requested
  226. static TokenizedFeature::Popup check_if_a_popup_window_is_requested(OrderedHashMap<String, String> const& tokenized_features)
  227. {
  228. // 1. If tokenizedFeatures is empty, then return false.
  229. if (tokenized_features.is_empty())
  230. return TokenizedFeature::Popup::No;
  231. // 2. If tokenizedFeatures["popup"] exists, then return the result of parsing tokenizedFeatures["popup"] as a boolean feature.
  232. if (auto popup_feature = tokenized_features.get("popup"sv); popup_feature.has_value())
  233. return parse_boolean_feature<TokenizedFeature::Popup>(*popup_feature);
  234. // https://html.spec.whatwg.org/multipage/window-object.html#window-feature-is-set
  235. auto check_if_a_window_feature_is_set = [&]<Enum T>(StringView feature_name, T default_value) {
  236. // 1. If tokenizedFeatures[featureName] exists, then return the result of parsing tokenizedFeatures[featureName] as a boolean feature.
  237. if (auto feature = tokenized_features.get(feature_name); feature.has_value())
  238. return parse_boolean_feature<T>(*feature);
  239. // 2. Return defaultValue.
  240. return default_value;
  241. };
  242. // 3. Let location be the result of checking if a window feature is set, given tokenizedFeatures, "location", and false.
  243. auto location = check_if_a_window_feature_is_set("location"sv, TokenizedFeature::Location::No);
  244. // 4. Let toolbar be the result of checking if a window feature is set, given tokenizedFeatures, "toolbar", and false.
  245. auto toolbar = check_if_a_window_feature_is_set("toolbar"sv, TokenizedFeature::Toolbar::No);
  246. // 5. If location and toolbar are both false, then return true.
  247. if (location == TokenizedFeature::Location::No && toolbar == TokenizedFeature::Toolbar::No)
  248. return TokenizedFeature::Popup::Yes;
  249. // 6. Let menubar be the result of checking if a window feature is set, given tokenizedFeatures, menubar", and false.
  250. auto menubar = check_if_a_window_feature_is_set("menubar"sv, TokenizedFeature::Menubar::No);
  251. // 7. If menubar is false, then return true.
  252. if (menubar == TokenizedFeature::Menubar::No)
  253. return TokenizedFeature::Popup::Yes;
  254. // 8. Let resizable be the result of checking if a window feature is set, given tokenizedFeatures, "resizable", and true.
  255. auto resizable = check_if_a_window_feature_is_set("resizable"sv, TokenizedFeature::Resizable::Yes);
  256. // 9. If resizable is false, then return true.
  257. if (resizable == TokenizedFeature::Resizable::No)
  258. return TokenizedFeature::Popup::Yes;
  259. // 10. Let scrollbars be the result of checking if a window feature is set, given tokenizedFeatures, "scrollbars", and false.
  260. auto scrollbars = check_if_a_window_feature_is_set("scrollbars"sv, TokenizedFeature::Scrollbars::No);
  261. // 11. If scrollbars is false, then return true.
  262. if (scrollbars == TokenizedFeature::Scrollbars::No)
  263. return TokenizedFeature::Popup::Yes;
  264. // 12. Let status be the result of checking if a window feature is set, given tokenizedFeatures, "status", and false.
  265. auto status = check_if_a_window_feature_is_set("status"sv, TokenizedFeature::Status::No);
  266. // 13. If status is false, then return true.
  267. if (status == TokenizedFeature::Status::No)
  268. return TokenizedFeature::Popup::Yes;
  269. // 14. Return false.
  270. return TokenizedFeature::Popup::No;
  271. }
  272. // https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps
  273. WebIDL::ExceptionOr<JS::GCPtr<WindowProxy>> Window::open_impl(StringView url, StringView target, StringView features)
  274. {
  275. // 1. If the event loop's termination nesting level is nonzero, return null.
  276. if (main_thread_event_loop().termination_nesting_level() != 0)
  277. return nullptr;
  278. // 2. Let sourceDocument be the entry global object's associated Document.
  279. auto& source_document = verify_cast<Window>(entry_global_object()).associated_document();
  280. // 3. If target is the empty string, then set target to "_blank".
  281. if (target.is_empty())
  282. target = "_blank"sv;
  283. // 4. Let tokenizedFeatures be the result of tokenizing features.
  284. auto tokenized_features = tokenize_open_features(features);
  285. // 5. Let noopener and noreferrer be false.
  286. auto no_opener = TokenizedFeature::NoOpener::No;
  287. auto no_referrer = TokenizedFeature::NoReferrer::No;
  288. // 6. If tokenizedFeatures["noopener"] exists, then:
  289. if (auto no_opener_feature = tokenized_features.get("noopener"sv); no_opener_feature.has_value()) {
  290. // 1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.
  291. no_opener = parse_boolean_feature<TokenizedFeature::NoOpener>(*no_opener_feature);
  292. // 2. Remove tokenizedFeatures["noopener"].
  293. tokenized_features.remove("noopener"sv);
  294. }
  295. // 7. If tokenizedFeatures["noreferrer"] exists, then:
  296. if (auto no_referrer_feature = tokenized_features.get("noreferrer"sv); no_referrer_feature.has_value()) {
  297. // 1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.
  298. no_referrer = parse_boolean_feature<TokenizedFeature::NoReferrer>(*no_referrer_feature);
  299. // 2. Remove tokenizedFeatures["noreferrer"].
  300. tokenized_features.remove("noreferrer"sv);
  301. }
  302. // 8. Let referrerPolicy be the empty string.
  303. auto referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString;
  304. // 9. If noreferrer is true, then set noopener to true and set referrerPolicy to "no-referrer".
  305. if (no_referrer == TokenizedFeature::NoReferrer::Yes) {
  306. no_opener = TokenizedFeature::NoOpener::Yes;
  307. referrer_policy = ReferrerPolicy::ReferrerPolicy::NoReferrer;
  308. }
  309. // 10. Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target, sourceDocument's node navigable, and noopener.
  310. VERIFY(source_document.navigable());
  311. auto [target_navigable, window_type] = source_document.navigable()->choose_a_navigable(target, no_opener);
  312. // 11. If targetNavigable is null, then return null.
  313. if (target_navigable == nullptr)
  314. return nullptr;
  315. // 12. If windowType is either "new and unrestricted" or "new with no opener", then:
  316. if (window_type == Navigable::WindowType::NewAndUnrestricted || window_type == Navigable::WindowType::NewWithNoOpener) {
  317. // 1. Set the target browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.
  318. target_navigable->set_is_popup(check_if_a_popup_window_is_requested(tokenized_features));
  319. // FIXME: 2. Set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]
  320. // NOTE: While this is not implemented yet, all of observable actions taken by this operation are optional (implementation-defined).
  321. // 3. Let urlRecord be the URL record about:blank.
  322. auto url_record = AK::URL("about:blank"sv);
  323. // 4. If url is not the empty string, then set urlRecord to the result of encoding-parsing a URL given url, relative to the entry settings object.
  324. if (!url.is_empty()) {
  325. url_record = entry_settings_object().parse_url(url);
  326. // 5. If urlRecord is failure, then throw a "SyntaxError" DOMException.
  327. if (!url_record.is_valid())
  328. return WebIDL::SyntaxError::create(realm(), "URL is not valid"_fly_string);
  329. }
  330. // 6. If urlRecord matches about:blank, then perform the URL and history update steps given targetNavigable's active document and urlRecord.
  331. if (url_matches_about_blank(url_record)) {
  332. // AD-HOC: Mark the initial about:blank for the new window as load complete
  333. // FIXME: We do this other places too when creating a new about:blank document. Perhaps it's worth a spec issue?
  334. HTML::HTMLParser::the_end(*target_navigable->active_document());
  335. perform_url_and_history_update_steps(*target_navigable->active_document(), url_record);
  336. }
  337. // 7. Otherwise, navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
  338. else {
  339. TRY(target_navigable->navigate({ .url = url_record, .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
  340. }
  341. }
  342. // 13. Otherwise:
  343. else {
  344. // 1. If url is not the empty string, then:
  345. if (!url.is_empty()) {
  346. // 1. Let urlRecord be the result of encoding-parsing a URL url, relative to the entry settings object.
  347. auto url_record = entry_settings_object().parse_url(url);
  348. // 2. If urlRecord is failure, then throw a "SyntaxError" DOMException.
  349. if (!url_record.is_valid())
  350. return WebIDL::SyntaxError::create(realm(), "URL is not valid"_fly_string);
  351. // 3. Navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
  352. TRY(target_navigable->navigate({ .url = url_record, .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
  353. }
  354. // 2. If noopener is false, then set targetNavigable's active browsing context's opener browsing context to sourceDocument's browsing context.
  355. if (no_opener == TokenizedFeature::NoOpener::No)
  356. target_navigable->active_browsing_context()->set_opener_browsing_context(source_document.browsing_context());
  357. }
  358. // 14. If noopener is true or windowType is "new with no opener", then return null.
  359. if (no_opener == TokenizedFeature::NoOpener::Yes || window_type == Navigable::WindowType::NewWithNoOpener)
  360. return nullptr;
  361. // 15. Return targetNavigable's active WindowProxy.
  362. return target_navigable->active_window_proxy();
  363. }
  364. bool Window::dispatch_event(DOM::Event& event)
  365. {
  366. return DOM::EventDispatcher::dispatch(*this, event, true);
  367. }
  368. Page& Window::page()
  369. {
  370. return associated_document().page();
  371. }
  372. Page const& Window::page() const
  373. {
  374. return associated_document().page();
  375. }
  376. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  377. {
  378. // FIXME: Many of these should be dependent on the hardware
  379. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  380. switch (media_feature) {
  381. case CSS::MediaFeatureID::AnyHover:
  382. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  383. case CSS::MediaFeatureID::AnyPointer:
  384. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  385. case CSS::MediaFeatureID::AspectRatio:
  386. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  387. case CSS::MediaFeatureID::Color:
  388. return CSS::MediaFeatureValue(8);
  389. case CSS::MediaFeatureID::ColorGamut:
  390. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  391. case CSS::MediaFeatureID::ColorIndex:
  392. return CSS::MediaFeatureValue(0);
  393. // FIXME: device-aspect-ratio
  394. case CSS::MediaFeatureID::DeviceHeight:
  395. return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().height()));
  396. case CSS::MediaFeatureID::DeviceWidth:
  397. return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().width()));
  398. case CSS::MediaFeatureID::DisplayMode:
  399. // FIXME: Detect if window is fullscreen
  400. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  401. case CSS::MediaFeatureID::DynamicRange:
  402. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  403. case CSS::MediaFeatureID::EnvironmentBlending:
  404. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  405. case CSS::MediaFeatureID::ForcedColors:
  406. return CSS::MediaFeatureValue(CSS::ValueID::None);
  407. case CSS::MediaFeatureID::Grid:
  408. return CSS::MediaFeatureValue(0);
  409. case CSS::MediaFeatureID::Height:
  410. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  411. case CSS::MediaFeatureID::HorizontalViewportSegments:
  412. return CSS::MediaFeatureValue(1);
  413. case CSS::MediaFeatureID::Hover:
  414. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  415. case CSS::MediaFeatureID::InvertedColors:
  416. return CSS::MediaFeatureValue(CSS::ValueID::None);
  417. case CSS::MediaFeatureID::Monochrome:
  418. return CSS::MediaFeatureValue(0);
  419. case CSS::MediaFeatureID::NavControls:
  420. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  421. case CSS::MediaFeatureID::Orientation:
  422. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  423. case CSS::MediaFeatureID::OverflowBlock:
  424. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  425. case CSS::MediaFeatureID::OverflowInline:
  426. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  427. case CSS::MediaFeatureID::Pointer:
  428. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  429. case CSS::MediaFeatureID::PrefersColorScheme: {
  430. switch (page().preferred_color_scheme()) {
  431. case CSS::PreferredColorScheme::Light:
  432. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  433. case CSS::PreferredColorScheme::Dark:
  434. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  435. case CSS::PreferredColorScheme::Auto:
  436. default:
  437. return CSS::MediaFeatureValue(page().palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  438. }
  439. }
  440. case CSS::MediaFeatureID::PrefersContrast:
  441. // FIXME: Make this a preference
  442. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  443. case CSS::MediaFeatureID::PrefersReducedData:
  444. // FIXME: Make this a preference
  445. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  446. case CSS::MediaFeatureID::PrefersReducedMotion:
  447. // FIXME: Make this a preference
  448. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  449. case CSS::MediaFeatureID::PrefersReducedTransparency:
  450. // FIXME: Make this a preference
  451. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  452. case CSS::MediaFeatureID::Resolution:
  453. return CSS::MediaFeatureValue(CSS::Resolution(device_pixel_ratio(), CSS::Resolution::Type::Dppx));
  454. case CSS::MediaFeatureID::Scan:
  455. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  456. case CSS::MediaFeatureID::Scripting:
  457. if (associated_document().is_scripting_enabled())
  458. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  459. return CSS::MediaFeatureValue(CSS::ValueID::None);
  460. case CSS::MediaFeatureID::Update:
  461. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  462. case CSS::MediaFeatureID::VerticalViewportSegments:
  463. return CSS::MediaFeatureValue(1);
  464. case CSS::MediaFeatureID::VideoColorGamut:
  465. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  466. case CSS::MediaFeatureID::VideoDynamicRange:
  467. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  468. case CSS::MediaFeatureID::Width:
  469. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  470. default:
  471. break;
  472. }
  473. return {};
  474. }
  475. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  476. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  477. {
  478. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  479. // fire an event named eventName at window, using PageTransitionEvent,
  480. // with the persisted attribute initialized to persisted,
  481. PageTransitionEventInit event_init {};
  482. event_init.persisted = persisted;
  483. auto event = PageTransitionEvent::create(associated_document().realm(), event_name, event_init);
  484. // ...the cancelable attribute initialized to true,
  485. event->set_cancelable(true);
  486. // the bubbles attribute initialized to true,
  487. event->set_bubbles(true);
  488. // and legacy target override flag set.
  489. dispatch_event(event);
  490. }
  491. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  492. WebIDL::ExceptionOr<JS::NonnullGCPtr<Storage>> Window::local_storage()
  493. {
  494. // FIXME: Implement according to spec.
  495. static HashMap<Origin, JS::Handle<Storage>> local_storage_per_origin;
  496. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<Storage> {
  497. return Storage::create(realm());
  498. });
  499. return JS::NonnullGCPtr { *storage };
  500. }
  501. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  502. WebIDL::ExceptionOr<JS::NonnullGCPtr<Storage>> Window::session_storage()
  503. {
  504. // FIXME: Implement according to spec.
  505. static HashMap<Origin, JS::Handle<Storage>> session_storage_per_origin;
  506. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<Storage> {
  507. return Storage::create(realm());
  508. });
  509. return JS::NonnullGCPtr { *storage };
  510. }
  511. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  512. bool Window::has_transient_activation() const
  513. {
  514. // The transient activation duration is expected be at most a few seconds, so that the user can possibly
  515. // perceive the link between an interaction with the page and the page calling the activation-gated API.
  516. auto transient_activation_duration = 5;
  517. // When the current high resolution time given W
  518. auto unsafe_shared_time = HighResolutionTime::unsafe_shared_current_time();
  519. auto current_time = HighResolutionTime::relative_high_resolution_time(unsafe_shared_time, realm().global_object());
  520. // is greater than or equal to the last activation timestamp in W
  521. if (current_time >= m_last_activation_timestamp) {
  522. // and less than the last activation timestamp in W plus the transient activation duration
  523. if (current_time < m_last_activation_timestamp + transient_activation_duration) {
  524. // then W is said to have transient activation.
  525. return true;
  526. }
  527. }
  528. return false;
  529. }
  530. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  531. void Window::start_an_idle_period()
  532. {
  533. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  534. // 2. Let pending_list be window's list of idle request callbacks.
  535. auto& pending_list = m_idle_request_callbacks;
  536. // 3. Let run_list be window's list of runnable idle callbacks.
  537. auto& run_list = m_runnable_idle_callbacks;
  538. run_list.extend(pending_list);
  539. // 4. Clear pending_list.
  540. pending_list.clear();
  541. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  542. if (run_list.is_empty())
  543. return;
  544. // 5. Queue a task on the queue associated with the idle-task task source,
  545. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  546. queue_global_task(Task::Source::IdleTask, *this, [this] {
  547. invoke_idle_callbacks();
  548. });
  549. }
  550. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  551. void Window::invoke_idle_callbacks()
  552. {
  553. auto& event_loop = main_thread_event_loop();
  554. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  555. // 2. Let now be the current time.
  556. auto now = HighResolutionTime::unsafe_shared_current_time();
  557. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  558. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  559. // 1. Pop the top callback from window's list of runnable idle callbacks.
  560. auto callback = m_runnable_idle_callbacks.take_first();
  561. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  562. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm());
  563. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  564. auto result = callback->invoke(deadline_arg);
  565. if (result.is_error())
  566. report_exception(result, realm());
  567. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  568. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  569. queue_global_task(Task::Source::IdleTask, *this, [this] {
  570. invoke_idle_callbacks();
  571. });
  572. }
  573. }
  574. void Window::set_associated_document(DOM::Document& document)
  575. {
  576. m_associated_document = &document;
  577. }
  578. void Window::set_current_event(DOM::Event* event)
  579. {
  580. m_current_event = event;
  581. }
  582. BrowsingContext const* Window::browsing_context() const
  583. {
  584. return m_associated_document->browsing_context();
  585. }
  586. BrowsingContext* Window::browsing_context()
  587. {
  588. return m_associated_document->browsing_context();
  589. }
  590. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#window-navigable
  591. JS::GCPtr<Navigable> Window::navigable() const
  592. {
  593. // A Window's navigable is the navigable whose active document is the Window's associated Document's, or null if there is no such navigable.
  594. return Navigable::navigable_with_active_document(*m_associated_document);
  595. }
  596. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-objects
  597. Vector<JS::NonnullGCPtr<Plugin>> Window::pdf_viewer_plugin_objects()
  598. {
  599. // Each Window object has a PDF viewer plugin objects list. If the user agent's PDF viewer supported is false, then it is the empty list.
  600. // Otherwise, it is a list containing five Plugin objects, whose names are, respectively:
  601. // 0. "PDF Viewer"
  602. // 1. "Chrome PDF Viewer"
  603. // 2. "Chromium PDF Viewer"
  604. // 3. "Microsoft Edge PDF Viewer"
  605. // 4. "WebKit built-in PDF"
  606. // The values of the above list form the PDF viewer plugin names list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-names
  607. if (!page().pdf_viewer_supported())
  608. return {};
  609. if (m_pdf_viewer_plugin_objects.is_empty()) {
  610. // FIXME: Propagate errors.
  611. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "PDF Viewer"_string));
  612. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chrome PDF Viewer"_string));
  613. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chromium PDF Viewer"_string));
  614. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Microsoft Edge PDF Viewer"_string));
  615. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "WebKit built-in PDF"_string));
  616. }
  617. return m_pdf_viewer_plugin_objects;
  618. }
  619. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-type-objects
  620. Vector<JS::NonnullGCPtr<MimeType>> Window::pdf_viewer_mime_type_objects()
  621. {
  622. // Each Window object has a PDF viewer mime type objects list. If the user agent's PDF viewer supported is false, then it is the empty list.
  623. // Otherwise, it is a list containing two MimeType objects, whose types are, respectively:
  624. // 0. "application/pdf"
  625. // 1. "text/pdf"
  626. // The values of the above list form the PDF viewer mime types list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-types
  627. if (!page().pdf_viewer_supported())
  628. return {};
  629. if (m_pdf_viewer_mime_type_objects.is_empty()) {
  630. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "application/pdf"_string));
  631. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "text/pdf"_string));
  632. }
  633. return m_pdf_viewer_mime_type_objects;
  634. }
  635. // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  636. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::CallbackType>> Window::count_queuing_strategy_size_function()
  637. {
  638. auto& realm = this->realm();
  639. if (!m_count_queuing_strategy_size_function) {
  640. // 1. Let steps be the following steps:
  641. auto steps = [](auto const&) {
  642. // 1. Return 1.
  643. return 1.0;
  644. };
  645. // 2. Let F be ! CreateBuiltinFunction(steps, 0, "size", « », globalObject’s relevant Realm).
  646. auto function = JS::NativeFunction::create(realm, move(steps), 0, "size", &realm);
  647. // 3. Set globalObject’s count queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  648. m_count_queuing_strategy_size_function = heap().allocate<WebIDL::CallbackType>(realm, *function, relevant_settings_object(*this));
  649. }
  650. return JS::NonnullGCPtr { *m_count_queuing_strategy_size_function };
  651. }
  652. // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  653. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::CallbackType>> Window::byte_length_queuing_strategy_size_function()
  654. {
  655. auto& realm = this->realm();
  656. if (!m_byte_length_queuing_strategy_size_function) {
  657. // 1. Let steps be the following steps, given chunk:
  658. auto steps = [](JS::VM& vm) {
  659. auto chunk = vm.argument(0);
  660. // 1. Return ? GetV(chunk, "byteLength").
  661. return chunk.get(vm, vm.names.byteLength);
  662. };
  663. // 2. Let F be ! CreateBuiltinFunction(steps, 1, "size", « », globalObject’s relevant Realm).
  664. auto function = JS::NativeFunction::create(realm, move(steps), 1, "size", &realm);
  665. // 3. Set globalObject’s byte length queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  666. m_byte_length_queuing_strategy_size_function = heap().allocate<WebIDL::CallbackType>(realm, *function, relevant_settings_object(*this));
  667. }
  668. return JS::NonnullGCPtr { *m_byte_length_queuing_strategy_size_function };
  669. }
  670. static bool s_inspector_object_exposed = false;
  671. static bool s_internals_object_exposed = false;
  672. void Window::set_inspector_object_exposed(bool exposed)
  673. {
  674. s_inspector_object_exposed = exposed;
  675. }
  676. void Window::set_internals_object_exposed(bool exposed)
  677. {
  678. s_internals_object_exposed = exposed;
  679. }
  680. WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  681. {
  682. auto& realm = this->realm();
  683. add_window_exposed_interfaces(*this);
  684. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WindowPrototype>(realm, "Window"_fly_string));
  685. Bindings::WindowGlobalMixin::initialize(realm, *this);
  686. WindowOrWorkerGlobalScopeMixin::initialize(realm);
  687. if (s_inspector_object_exposed)
  688. define_direct_property("inspector", heap().allocate<Internals::Inspector>(realm, realm), JS::default_attributes);
  689. if (s_internals_object_exposed)
  690. define_direct_property("internals", heap().allocate<Internals::Internals>(realm, realm), JS::default_attributes);
  691. return {};
  692. }
  693. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  694. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  695. {
  696. // 1. Return ? SetImmutablePrototype(O, V).
  697. return set_immutable_prototype(prototype);
  698. }
  699. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  700. JS::NonnullGCPtr<WindowProxy> Window::window() const
  701. {
  702. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  703. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  704. }
  705. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  706. JS::NonnullGCPtr<WindowProxy> Window::self() const
  707. {
  708. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  709. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  710. }
  711. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-2
  712. JS::NonnullGCPtr<DOM::Document const> Window::document() const
  713. {
  714. // The document getter steps are to return this's associated Document.
  715. return associated_document();
  716. }
  717. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-name
  718. String Window::name() const
  719. {
  720. // 1. If this's navigable is null, then return the empty string.
  721. if (!navigable())
  722. return String {};
  723. // 2. Return this's navigable's target name.
  724. return navigable()->target_name();
  725. }
  726. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#apis-for-creating-and-navigating-browsing-contexts-by-name:dom-name
  727. void Window::set_name(String const& name)
  728. {
  729. // 1. If this's navigable is null, then return.
  730. if (!navigable())
  731. return;
  732. // 2. Set this's navigable's active session history entry's document state's navigable target name to the given value.
  733. navigable()->active_session_history_entry()->document_state->set_navigable_target_name(name);
  734. }
  735. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-status
  736. String Window::status() const
  737. {
  738. // the status attribute on the Window object must, on getting, return the last string it was set to
  739. return m_status;
  740. }
  741. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-status
  742. void Window::set_status(String const& status)
  743. {
  744. // on setting, must set itself to the new value.
  745. m_status = status;
  746. }
  747. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location
  748. JS::NonnullGCPtr<Location> Window::location()
  749. {
  750. auto& realm = this->realm();
  751. // The Window object's location getter steps are to return this's Location object.
  752. if (!m_location)
  753. m_location = heap().allocate<Location>(realm, realm);
  754. return JS::NonnullGCPtr { *m_location };
  755. }
  756. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-history
  757. JS::NonnullGCPtr<History> Window::history() const
  758. {
  759. // The history getter steps are to return this's associated Document's history object.
  760. return associated_document().history();
  761. }
  762. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  763. void Window::focus()
  764. {
  765. // 1. Let current be this Window object's navigable.
  766. auto current = navigable();
  767. // 2. If current is null, then return.
  768. if (!current)
  769. return;
  770. // 3. Run the focusing steps with current.
  771. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  772. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  773. run_focusing_steps(current->active_document());
  774. // FIXME: 4. If current is a top-level traversable, user agents are encouraged to trigger some sort of notification to
  775. // indicate to the user that the page is attempting to gain focus.
  776. }
  777. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  778. JS::NonnullGCPtr<WindowProxy> Window::frames() const
  779. {
  780. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  781. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  782. }
  783. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  784. u32 Window::length()
  785. {
  786. // The length getter steps are to return this's associated Document's document-tree child navigables's size.
  787. return associated_document().document_tree_child_navigables().size();
  788. }
  789. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-top
  790. JS::GCPtr<WindowProxy const> Window::top() const
  791. {
  792. // 1. If this's navigable is null, then return null.
  793. auto navigable = this->navigable();
  794. if (!navigable)
  795. return {};
  796. // 2. Return this's navigable's top-level traversable's active WindowProxy.
  797. return navigable->top_level_traversable()->active_window_proxy();
  798. }
  799. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-parent
  800. JS::GCPtr<WindowProxy const> Window::parent() const
  801. {
  802. // 1. Let navigable be this's navigable.
  803. auto navigable = this->navigable();
  804. // 2. If navigable is null, then return null.
  805. if (!navigable)
  806. return {};
  807. // 3. If navigable's parent is not null, then set navigable to navigable's parent.
  808. if (auto parent = navigable->parent())
  809. navigable = parent;
  810. // 4. Return navigable's active WindowProxy.
  811. return navigable->active_window_proxy();
  812. }
  813. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-frameelement
  814. JS::GCPtr<DOM::Element const> Window::frame_element() const
  815. {
  816. // 1. Let current be this's node navigable.
  817. auto current = navigable();
  818. // 2. If current is null, then return null.
  819. if (!current)
  820. return {};
  821. // 3. Let container be current's container.
  822. auto container = current->container();
  823. // 4. If container is null, then return null.
  824. if (!container)
  825. return {};
  826. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  827. if (!container->document().origin().is_same_origin_domain(current_settings_object().origin()))
  828. return {};
  829. // 6. Return container.
  830. return container;
  831. }
  832. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-open
  833. WebIDL::ExceptionOr<JS::GCPtr<WindowProxy>> Window::open(Optional<String> const& url, Optional<String> const& target, Optional<String> const& features)
  834. {
  835. // The open(url, target, features) method steps are to run the window open steps with url, target, and features.
  836. return open_impl(*url, *target, *features);
  837. }
  838. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  839. JS::NonnullGCPtr<Navigator> Window::navigator()
  840. {
  841. auto& realm = this->realm();
  842. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  843. if (!m_navigator)
  844. m_navigator = heap().allocate<Navigator>(realm, realm);
  845. return JS::NonnullGCPtr { *m_navigator };
  846. }
  847. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  848. void Window::alert(String const& message)
  849. {
  850. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  851. // Note: This method is defined using two overloads, instead of using an optional argument,
  852. // for historical reasons. The practical impact of this is that alert(undefined) is
  853. // treated as alert("undefined"), but alert() is treated as alert("").
  854. // FIXME: Make this fully spec compliant.
  855. page().did_request_alert(message);
  856. }
  857. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  858. bool Window::confirm(Optional<String> const& message)
  859. {
  860. // FIXME: Make this fully spec compliant.
  861. // NOTE: `message` has an IDL-provided default value and is never empty.
  862. return page().did_request_confirm(*message);
  863. }
  864. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  865. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  866. {
  867. // FIXME: Make this fully spec compliant.
  868. return page().did_request_prompt(*message, *default_);
  869. }
  870. // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
  871. WebIDL::ExceptionOr<void> Window::window_post_message_steps(JS::Value message, WindowPostMessageOptions const& options)
  872. {
  873. // 1. Let targetRealm be targetWindow's realm.
  874. auto& target_realm = this->realm();
  875. // 2. Let incumbentSettings be the incumbent settings object.
  876. auto& incumbent_settings = incumbent_settings_object();
  877. // 3. Let targetOrigin be options["targetOrigin"].
  878. Variant<String, Origin> target_origin = options.target_origin;
  879. // 4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.
  880. if (options.target_origin == "/"sv) {
  881. target_origin = incumbent_settings.origin();
  882. }
  883. // 5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*), then:
  884. else if (options.target_origin != "*"sv) {
  885. // 1. Let parsedURL be the result of running the URL parser on targetOrigin.
  886. auto parsed_url = URL::parse(options.target_origin);
  887. // 2. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  888. if (!parsed_url.is_valid())
  889. return WebIDL::SyntaxError::create(target_realm, MUST(String::formatted("Invalid URL for targetOrigin: '{}'", options.target_origin)));
  890. // 3. Set targetOrigin to parsedURL's origin.
  891. target_origin = URL::url_origin(parsed_url);
  892. }
  893. // 6. Let transfer be options["transfer"].
  894. auto& transfer = options.transfer;
  895. // 7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
  896. auto serialize_with_transfer_result = TRY(structured_serialize_with_transfer(target_realm.vm(), message, transfer));
  897. // 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
  898. queue_global_task(Task::Source::PostedMessage, *this, [this, serialize_with_transfer_result = move(serialize_with_transfer_result), target_origin = move(target_origin), &incumbent_settings, &target_realm]() mutable {
  899. // 1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's
  900. // associated Document's origin is not same origin with targetOrigin, then return.
  901. // NOTE: Due to step 4 and 5 above, the only time it's not '*' is if target_origin contains an Origin.
  902. if (!target_origin.has<String>()) {
  903. auto const& actual_target_origin = target_origin.get<Origin>();
  904. if (!document()->origin().is_same_origin(actual_target_origin))
  905. return;
  906. }
  907. // 2. Let origin be the serialization of incumbentSettings's origin.
  908. auto origin = incumbent_settings.origin().serialize();
  909. // 3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
  910. auto& source = verify_cast<WindowProxy>(incumbent_settings.realm().global_environment().global_this_value());
  911. // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
  912. auto& settings_object = Bindings::host_defined_environment_settings_object(target_realm);
  913. auto temporary_execution_context = TemporaryExecutionContext { settings_object };
  914. auto deserialize_record_or_error = structured_deserialize_with_transfer(vm(), serialize_with_transfer_result);
  915. // If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent,
  916. // with the origin attribute initialized to origin and the source attribute initialized to source, and then return.
  917. if (deserialize_record_or_error.is_exception()) {
  918. MessageEventInit message_event_init {};
  919. message_event_init.origin = MUST(String::from_byte_string(origin));
  920. message_event_init.source = JS::make_handle(source);
  921. auto message_error_event = MessageEvent::create(target_realm, EventNames::messageerror, message_event_init);
  922. dispatch_event(message_error_event);
  923. return;
  924. }
  925. // 5. Let messageClone be deserializeRecord.[[Deserialized]].
  926. auto deserialize_record = deserialize_record_or_error.release_value();
  927. auto message_clone = deserialize_record.deserialized;
  928. // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]],
  929. // if any, maintaining their relative order.
  930. // FIXME: Use a FrozenArray
  931. Vector<JS::Handle<JS::Object>> new_ports;
  932. for (auto const& object : deserialize_record.transferred_values) {
  933. if (is<HTML::MessagePort>(*object)) {
  934. new_ports.append(object);
  935. }
  936. }
  937. // 7. Fire an event named message at targetWindow, using MessageEvent, with the origin attribute initialized to origin,
  938. // the source attribute initialized to source, the data attribute initialized to messageClone, and the ports attribute
  939. // initialized to newPorts.
  940. MessageEventInit message_event_init {};
  941. message_event_init.origin = MUST(String::from_byte_string(origin));
  942. message_event_init.source = JS::make_handle(source);
  943. message_event_init.data = message_clone;
  944. message_event_init.ports = move(new_ports);
  945. auto message_event = MessageEvent::create(target_realm, EventNames::message, message_event_init);
  946. dispatch_event(message_event);
  947. });
  948. return {};
  949. }
  950. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage-options
  951. WebIDL::ExceptionOr<void> Window::post_message(JS::Value message, WindowPostMessageOptions const& options)
  952. {
  953. // The Window interface's postMessage(message, options) method steps are to run the window post message steps given
  954. // this, message, and options.
  955. return window_post_message_steps(message, options);
  956. }
  957. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  958. WebIDL::ExceptionOr<void> Window::post_message(JS::Value message, String const& target_origin, Vector<JS::Handle<JS::Object>> const& transfer)
  959. {
  960. // The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message
  961. // steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».
  962. return window_post_message_steps(message, WindowPostMessageOptions { { .transfer = transfer }, target_origin });
  963. }
  964. // https://dom.spec.whatwg.org/#dom-window-event
  965. Variant<JS::Handle<DOM::Event>, JS::Value> Window::event() const
  966. {
  967. // The event getter steps are to return this’s current event.
  968. if (auto* current_event = this->current_event())
  969. return make_handle(const_cast<DOM::Event&>(*current_event));
  970. return JS::js_undefined();
  971. }
  972. // https://w3c.github.io/csswg-drafts/cssom/#dom-window-getcomputedstyle
  973. JS::NonnullGCPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element, Optional<String> const& pseudo_element) const
  974. {
  975. // FIXME: Make this fully spec compliant.
  976. (void)pseudo_element;
  977. return heap().allocate<CSS::ResolvedCSSStyleDeclaration>(realm(), element);
  978. }
  979. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-matchmedia
  980. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSS::MediaQueryList>> Window::match_media(String const& query)
  981. {
  982. // 1. Let parsed media query list be the result of parsing query.
  983. auto parsed_media_query_list = parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), query);
  984. // 2. Return a new MediaQueryList object, with this's associated Document as the document, with parsed media query list as its associated media query list.
  985. auto media_query_list = heap().allocate<CSS::MediaQueryList>(realm(), associated_document(), move(parsed_media_query_list));
  986. associated_document().add_media_query_list(media_query_list);
  987. return media_query_list;
  988. }
  989. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screen
  990. JS::NonnullGCPtr<CSS::Screen> Window::screen()
  991. {
  992. // The screen attribute must return the Screen object associated with the Window object.
  993. if (!m_screen)
  994. m_screen = heap().allocate<CSS::Screen>(realm(), *this);
  995. return JS::NonnullGCPtr { *m_screen };
  996. }
  997. JS::GCPtr<CSS::VisualViewport> Window::visual_viewport()
  998. {
  999. // If the associated document is fully active, the visualViewport attribute must return
  1000. // the VisualViewport object associated with the Window object’s associated document.
  1001. if (associated_document().is_fully_active())
  1002. return associated_document().visual_viewport();
  1003. // Otherwise, it must return null.
  1004. return nullptr;
  1005. }
  1006. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerwidth
  1007. i32 Window::inner_width() const
  1008. {
  1009. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  1010. // or zero if there is no viewport.
  1011. if (auto const navigable = associated_document().navigable())
  1012. return navigable->viewport_rect().width().to_int();
  1013. return 0;
  1014. }
  1015. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerheight
  1016. i32 Window::inner_height() const
  1017. {
  1018. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  1019. // or zero if there is no viewport.
  1020. if (auto const navigable = associated_document().navigable())
  1021. return navigable->viewport_rect().height().to_int();
  1022. return 0;
  1023. }
  1024. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollx
  1025. double Window::scroll_x() const
  1026. {
  1027. // The scrollX attribute must return the x-coordinate, relative to the initial containing block origin,
  1028. // of the left of the viewport, or zero if there is no viewport.
  1029. if (auto const navigable = associated_document().navigable())
  1030. return navigable->viewport_rect().x().to_double();
  1031. return 0;
  1032. }
  1033. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly
  1034. double Window::scroll_y() const
  1035. {
  1036. // The scrollY attribute must return the y-coordinate, relative to the initial containing block origin,
  1037. // of the top of the viewport, or zero if there is no viewport.
  1038. if (auto const navigable = associated_document().navigable())
  1039. return navigable->viewport_rect().y().to_double();
  1040. return 0;
  1041. }
  1042. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  1043. void Window::scroll(ScrollToOptions const& options)
  1044. {
  1045. // 4. If there is no viewport, abort these steps.
  1046. auto navigable = associated_document().navigable();
  1047. if (!navigable)
  1048. return;
  1049. // 1. If invoked with one argument, follow these substeps:
  1050. // 1. Let options be the argument.
  1051. auto viewport_rect = navigable->viewport_rect().to_type<float>();
  1052. // 2. Let x be the value of the left dictionary member of options, if present, or the viewport’s current scroll
  1053. // position on the x axis otherwise.
  1054. auto x = options.left.value_or(viewport_rect.x());
  1055. // 3. Let y be the value of the top dictionary member of options, if present, or the viewport’s current scroll
  1056. // position on the y axis otherwise.
  1057. auto y = options.top.value_or(viewport_rect.y());
  1058. // 3. Normalize non-finite values for x and y.
  1059. x = JS::Value(x).is_finite_number() ? x : 0;
  1060. y = JS::Value(y).is_finite_number() ? y : 0;
  1061. // 5. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any.
  1062. auto viewport_width = viewport_rect.width();
  1063. // 6. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any.
  1064. auto viewport_height = viewport_rect.height();
  1065. auto const document = navigable->active_document();
  1066. VERIFY(document);
  1067. // Make sure layout is up-to-date before looking at scrollable overflow metrics.
  1068. document->update_layout();
  1069. VERIFY(document->paintable_box());
  1070. auto scrolling_area = document->paintable_box()->scrollable_overflow_rect()->to_type<float>();
  1071. // 7. FIXME: For now we always assume overflow direction is rightward
  1072. // -> If the viewport has rightward overflow direction
  1073. // Let x be max(0, min(x, viewport scrolling area width - viewport width)).
  1074. x = max(0.0f, min(x, scrolling_area.width() - viewport_width));
  1075. // -> If the viewport has leftward overflow direction
  1076. // Let x be min(0, max(x, viewport width - viewport scrolling area width)).
  1077. // 8. FIXME: For now we always assume overflow direction is downward
  1078. // -> If the viewport has downward overflow direction
  1079. // Let y be max(0, min(y, viewport scrolling area height - viewport height)).
  1080. y = max(0.0f, min(y, scrolling_area.height() - viewport_height));
  1081. // -> If the viewport has upward overflow direction
  1082. // Let y be min(0, max(y, viewport height - viewport scrolling area height)).
  1083. // FIXME: 9. Let position be the scroll position the viewport would have by aligning the x-coordinate x of the viewport
  1084. // scrolling area with the left of the viewport and aligning the y-coordinate y of the viewport scrolling area
  1085. // with the top of the viewport.
  1086. auto position = Gfx::FloatPoint { x, y };
  1087. // 10. If position is the same as the viewport’s current scroll position, and the viewport does not have an ongoing
  1088. // smooth scroll, abort these steps.
  1089. if (position == viewport_rect.location())
  1090. return;
  1091. // 11. Let document be the viewport’s associated Document.
  1092. // NOTE: document is already defined above.
  1093. // 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is
  1094. // one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.
  1095. navigable->perform_scroll_of_viewport({ x, y });
  1096. }
  1097. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  1098. void Window::scroll(double x, double y)
  1099. {
  1100. // 2. If invoked with two arguments, follow these substeps:
  1101. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1102. auto options = ScrollToOptions {};
  1103. // 2. Let x and y be the arguments, respectively.
  1104. options.left = x;
  1105. options.top = y;
  1106. scroll(options);
  1107. }
  1108. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1109. void Window::scroll_by(ScrollToOptions options)
  1110. {
  1111. // 2. Normalize non-finite values for the left and top dictionary members of options.
  1112. auto x = options.left.value_or(0);
  1113. auto y = options.top.value_or(0);
  1114. x = JS::Value(x).is_finite_number() ? x : 0;
  1115. y = JS::Value(y).is_finite_number() ? y : 0;
  1116. // 3. Add the value of scrollX to the left dictionary member.
  1117. options.left = x + scroll_x();
  1118. // 4. Add the value of scrollY to the top dictionary member.
  1119. options.top = y + scroll_y();
  1120. // 5. Act as if the scroll() method was invoked with options as the only argument.
  1121. scroll(options);
  1122. }
  1123. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1124. void Window::scroll_by(double x, double y)
  1125. {
  1126. // 1. If invoked with two arguments, follow these substeps:
  1127. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1128. auto options = ScrollToOptions {};
  1129. // 2. Let x and y be the arguments, respectively.
  1130. // 3. Let the left dictionary member of options have the value x.
  1131. options.left = x;
  1132. // 4. Let the top dictionary member of options have the value y.
  1133. options.top = y;
  1134. scroll_by(options);
  1135. }
  1136. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screenx
  1137. i32 Window::screen_x() const
  1138. {
  1139. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed
  1140. // screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  1141. return page().window_position().x().value();
  1142. }
  1143. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny
  1144. i32 Window::screen_y() const
  1145. {
  1146. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the
  1147. // Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  1148. return page().window_position().y().value();
  1149. }
  1150. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth
  1151. i32 Window::outer_width() const
  1152. {
  1153. // The outerWidth attribute must return the width of the client window. If there is no client window this
  1154. // attribute must return zero.
  1155. return page().window_size().width().value();
  1156. }
  1157. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight
  1158. i32 Window::outer_height() const
  1159. {
  1160. // The outerHeight attribute must return the height of the client window. If there is no client window this
  1161. // attribute must return zero.
  1162. return page().window_size().height().value();
  1163. }
  1164. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio
  1165. double Window::device_pixel_ratio() const
  1166. {
  1167. // 1. If there is no output device, return 1 and abort these steps.
  1168. // 2. Let CSS pixel size be the size of a CSS pixel at the current page zoom and using a scale factor of 1.0.
  1169. // 3. Let device pixel size be the vertical size of a device pixel of the output device.
  1170. // 4. Return the result of dividing CSS pixel size by device pixel size.
  1171. return page().client().device_pixels_per_css_pixel();
  1172. }
  1173. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe
  1174. i32 Window::request_animation_frame(WebIDL::CallbackType& callback)
  1175. {
  1176. // FIXME: Make this fully spec compliant. Currently implements a mix of 'requestAnimationFrame()' and 'run the animation frame callbacks'.
  1177. return m_animation_frame_callback_driver.add([this, callback = JS::make_handle(callback)](double now) {
  1178. // 3. Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.
  1179. auto result = WebIDL::invoke_callback(*callback, {}, JS::Value(now));
  1180. if (result.is_error())
  1181. report_exception(result, realm());
  1182. });
  1183. }
  1184. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animationframeprovider-cancelanimationframe
  1185. void Window::cancel_animation_frame(i32 handle)
  1186. {
  1187. // 1. If this is not supported, then throw a "NotSupportedError" DOMException.
  1188. // NOTE: Doesn't apply in this Window-specific implementation.
  1189. // 2. Let callbacks be this's target object's map of animation frame callbacks.
  1190. // 3. Remove callbacks[handle].
  1191. m_animation_frame_callback_driver.remove(handle);
  1192. }
  1193. // https://w3c.github.io/requestidlecallback/#dom-window-requestidlecallback
  1194. u32 Window::request_idle_callback(WebIDL::CallbackType& callback, RequestIdleCallback::IdleRequestOptions const& options)
  1195. {
  1196. // 1. Let window be this Window object.
  1197. // 2. Increment the window's idle callback identifier by one.
  1198. m_idle_callback_identifier++;
  1199. // 3. Let handle be the current value of window's idle callback identifier.
  1200. auto handle = m_idle_callback_identifier;
  1201. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  1202. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  1203. return WebIDL::invoke_callback(*callback, {}, deadline.ptr());
  1204. };
  1205. m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  1206. // 5. Return handle and then continue running this algorithm asynchronously.
  1207. return handle;
  1208. // FIXME: 6. If the timeout property is present in options and has a positive value:
  1209. // FIXME: 1. Wait for timeout milliseconds.
  1210. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  1211. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  1212. // FIXME: 4. Queue a task on the queue associated with the idle-task task source, which performs the invoke idle callback timeout algorithm, passing handle and window as arguments.
  1213. (void)options;
  1214. }
  1215. // https://w3c.github.io/requestidlecallback/#dom-window-cancelidlecallback
  1216. void Window::cancel_idle_callback(u32 handle)
  1217. {
  1218. // 1. Let window be this Window object.
  1219. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  1220. // that is associated with the value handle.
  1221. // 3. If there is such an entry, remove it from both window's list of idle request callbacks and the list of runnable idle callbacks.
  1222. m_idle_request_callbacks.remove_first_matching([&](auto& callback) {
  1223. return callback->handle() == handle;
  1224. });
  1225. m_runnable_idle_callbacks.remove_first_matching([&](auto& callback) {
  1226. return callback->handle() == handle;
  1227. });
  1228. }
  1229. // https://w3c.github.io/selection-api/#dom-window-getselection
  1230. JS::GCPtr<Selection::Selection> Window::get_selection() const
  1231. {
  1232. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1233. return associated_document().get_selection();
  1234. }
  1235. // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
  1236. JS::NonnullGCPtr<HighResolutionTime::Performance> Window::performance()
  1237. {
  1238. if (!m_performance)
  1239. m_performance = heap().allocate<HighResolutionTime::Performance>(realm(), *this);
  1240. return JS::NonnullGCPtr { *m_performance };
  1241. }
  1242. // https://w3c.github.io/webcrypto/#dom-windoworworkerglobalscope-crypto
  1243. JS::NonnullGCPtr<Crypto::Crypto> Window::crypto()
  1244. {
  1245. auto& realm = this->realm();
  1246. if (!m_crypto)
  1247. m_crypto = heap().allocate<Crypto::Crypto>(realm, realm);
  1248. return JS::NonnullGCPtr { *m_crypto };
  1249. }
  1250. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation
  1251. JS::NonnullGCPtr<Navigation> Window::navigation()
  1252. {
  1253. // Upon creation of the Window object, its navigation API must be set
  1254. // to a new Navigation object created in the Window object's relevant realm.
  1255. if (!m_navigation) {
  1256. auto& realm = relevant_realm(*this);
  1257. m_navigation = heap().allocate<Navigation>(realm, realm);
  1258. }
  1259. // The navigation getter steps are to return this's navigation API.
  1260. return *m_navigation;
  1261. }
  1262. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-window-customelements
  1263. JS::NonnullGCPtr<CustomElementRegistry> Window::custom_elements()
  1264. {
  1265. auto& realm = this->realm();
  1266. // The customElements attribute of the Window interface must return the CustomElementRegistry object for that Window object.
  1267. if (!m_custom_element_registry)
  1268. m_custom_element_registry = heap().allocate<CustomElementRegistry>(realm, realm);
  1269. return JS::NonnullGCPtr { *m_custom_element_registry };
  1270. }
  1271. // https://html.spec.whatwg.org/#document-tree-child-navigable-target-name-property-set
  1272. OrderedHashMap<FlyString, JS::NonnullGCPtr<Navigable>> Window::document_tree_child_navigable_target_name_property_set()
  1273. {
  1274. // The document-tree child navigable target name property set of a Window object window is the return value of running these steps:
  1275. // 1. Let children be the document-tree child navigables of window's associated Document.
  1276. auto children = associated_document().document_tree_child_navigables();
  1277. // 2. Let firstNamedChildren be an empty ordered set.
  1278. OrderedHashMap<FlyString, JS::NonnullGCPtr<Navigable>> first_named_children;
  1279. // 3. For each navigable of children:
  1280. for (auto const& navigable : children) {
  1281. // 1. Let name be navigable's target name.
  1282. auto const& name = navigable->target_name();
  1283. // 2. If name is the empty string, then continue.
  1284. if (name.is_empty())
  1285. continue;
  1286. // 3. If firstNamedChildren contains a navigable whose target name is name, then continue.
  1287. if (first_named_children.contains(name))
  1288. continue;
  1289. // 4. Append navigable to firstNamedChildren.
  1290. (void)first_named_children.set(name, *navigable);
  1291. }
  1292. // 4. Let names be an empty ordered set.
  1293. OrderedHashMap<FlyString, JS::NonnullGCPtr<Navigable>> names;
  1294. // 5. For each navigable of firstNamedChildren:
  1295. for (auto const& [name, navigable] : first_named_children) {
  1296. // 1. Let name be navigable's target name.
  1297. // 2. If navigable's active document's origin is same origin with window's relevant settings object's origin, then append name to names.
  1298. if (navigable->active_document()->origin().is_same_origin(relevant_settings_object(*this).origin()))
  1299. names.set(name, *navigable);
  1300. }
  1301. return names;
  1302. }
  1303. // https://html.spec.whatwg.org/#named-access-on-the-window-object
  1304. Vector<FlyString> Window::supported_property_names() const
  1305. {
  1306. // FIXME: Make the const-correctness of the methods this method calls less cowboy.
  1307. auto& mutable_this = const_cast<Window&>(*this);
  1308. // The Window object supports named properties.
  1309. // The supported property names of a Window object window at any moment consist of the following,
  1310. // in tree order according to the element that contributed them, ignoring later duplicates:
  1311. HashTable<FlyString> property_names;
  1312. // - window's document-tree child navigable target name property set;
  1313. auto child_navigable_property_set = mutable_this.document_tree_child_navigable_target_name_property_set();
  1314. for (auto& entry : child_navigable_property_set)
  1315. property_names.set(entry.key, AK::HashSetExistingEntryBehavior::Keep);
  1316. // - the value of the name content attribute for all embed, form, img, and object elements
  1317. // that have a non-empty name content attribute and are in a document tree with window's associated Document as their root; and
  1318. // - the value of the id content attribute for all HTML elements that have a non-empty id content attribute
  1319. // and are in a document tree with window's associated Document as their root.
  1320. associated_document().for_each_in_subtree_of_type<DOM::Element>([&property_names](auto& element) -> IterationDecision {
  1321. if (is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element)) {
  1322. if (element.name().has_value())
  1323. property_names.set(element.name().value(), AK::HashSetExistingEntryBehavior::Keep);
  1324. }
  1325. if (auto const& name = element.id(); name.has_value())
  1326. property_names.set(name.value().to_string(), AK::HashSetExistingEntryBehavior::Keep);
  1327. return IterationDecision::Continue;
  1328. });
  1329. return property_names.values();
  1330. }
  1331. // https://html.spec.whatwg.org/#named-access-on-the-window-object
  1332. WebIDL::ExceptionOr<JS::Value> Window::named_item_value(FlyString const& name) const
  1333. {
  1334. // FIXME: Make the const-correctness of the methods this method calls less cowboy.
  1335. auto& mutable_this = const_cast<Window&>(*this);
  1336. // To determine the value of a named property name in a Window object window, the user agent must return the value obtained using the following steps:
  1337. // 1. Let objects be the list of named objects of window with the name name.
  1338. // NOTE: There will be at least one such object, since the algorithm would otherwise not have been invoked by Web IDL.
  1339. auto objects = mutable_this.named_objects(name);
  1340. // 2. If objects contains a navigable, then:
  1341. if (!objects.navigables.is_empty()) {
  1342. // 1. Let container be the first navigable container in window's associated Document's descendants whose content navigable is in objects.
  1343. JS::GCPtr<NavigableContainer> container = nullptr;
  1344. mutable_this.associated_document().for_each_in_subtree_of_type<HTML::NavigableContainer>([&](HTML::NavigableContainer& navigable_container) {
  1345. if (!navigable_container.content_navigable())
  1346. return IterationDecision::Continue;
  1347. if (objects.navigables.contains_slow(JS::NonnullGCPtr { *navigable_container.content_navigable() })) {
  1348. container = navigable_container;
  1349. return IterationDecision::Break;
  1350. }
  1351. return IterationDecision::Continue;
  1352. });
  1353. // 2. Return container's content navigable's active WindowProxy.
  1354. VERIFY(container);
  1355. return container->content_navigable()->active_window_proxy();
  1356. }
  1357. // 3. Otherwise, if objects has only one element, return that element.
  1358. if (objects.elements.size() == 1)
  1359. return objects.elements[0];
  1360. // 4. Otherwise return an HTMLCollection rooted at window's associated Document,
  1361. // whose filter matches only named objects of window with the name name. (By definition, these will all be elements.)
  1362. return DOM::HTMLCollection::create(mutable_this.associated_document(), DOM::HTMLCollection::Scope::Descendants, [name](auto& element) -> bool {
  1363. if ((is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element))
  1364. && (element.name() == name))
  1365. return true;
  1366. return element.id() == name;
  1367. });
  1368. }
  1369. // https://html.spec.whatwg.org/#dom-window-nameditem-filter
  1370. Window::NamedObjects Window::named_objects(StringView name)
  1371. {
  1372. // NOTE: Since the Window interface has the [Global] extended attribute, its named properties
  1373. // follow the rules for named properties objects rather than legacy platform objects.
  1374. // Named objects of Window object window with the name name, for the purposes of the above algorithm, consist of the following:
  1375. NamedObjects objects;
  1376. // document-tree child navigables of window's associated Document whose target name is name;
  1377. auto children = associated_document().document_tree_child_navigables();
  1378. for (auto& navigable : children) {
  1379. if (navigable->target_name() == name) {
  1380. objects.navigables.append(*navigable);
  1381. }
  1382. }
  1383. // embed, form, img, or object elements that have a name content attribute whose value is name
  1384. // and are in a document tree with window's associated Document as their root; and
  1385. // HTML elements that have an id content attribute whose value is name and are in a document tree with window's associated Document as their root.
  1386. associated_document().for_each_in_subtree_of_type<DOM::Element>([&objects, &name](auto& element) -> IterationDecision {
  1387. if ((is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element))
  1388. && (element.name() == name))
  1389. objects.elements.append(element);
  1390. else if (element.id() == name)
  1391. objects.elements.append(element);
  1392. return IterationDecision::Continue;
  1393. });
  1394. return objects;
  1395. }
  1396. }