Window.cpp 74 KB

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