Window.cpp 75 KB

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