Window.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. /*
  2. * Copyright (c) 2020-2022, 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/Completion.h>
  14. #include <LibJS/Runtime/Error.h>
  15. #include <LibJS/Runtime/FunctionObject.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/Shape.h>
  18. #include <LibTextCodec/Decoder.h>
  19. #include <LibWeb/Bindings/CSSNamespace.h>
  20. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  21. #include <LibWeb/Bindings/FetchMethod.h>
  22. #include <LibWeb/Bindings/Replaceable.h>
  23. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  24. #include <LibWeb/Bindings/WindowPrototype.h>
  25. #include <LibWeb/CSS/MediaQueryList.h>
  26. #include <LibWeb/CSS/Parser/Parser.h>
  27. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  28. #include <LibWeb/CSS/Screen.h>
  29. #include <LibWeb/Crypto/Crypto.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <LibWeb/DOM/Event.h>
  32. #include <LibWeb/DOM/EventDispatcher.h>
  33. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  34. #include <LibWeb/HTML/BrowsingContext.h>
  35. #include <LibWeb/HTML/EventHandler.h>
  36. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  37. #include <LibWeb/HTML/Focus.h>
  38. #include <LibWeb/HTML/Location.h>
  39. #include <LibWeb/HTML/MessageEvent.h>
  40. #include <LibWeb/HTML/Navigator.h>
  41. #include <LibWeb/HTML/Origin.h>
  42. #include <LibWeb/HTML/PageTransitionEvent.h>
  43. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  44. #include <LibWeb/HTML/Scripting/Environments.h>
  45. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  46. #include <LibWeb/HTML/Storage.h>
  47. #include <LibWeb/HTML/StructuredSerialize.h>
  48. #include <LibWeb/HTML/Timer.h>
  49. #include <LibWeb/HTML/Window.h>
  50. #include <LibWeb/HTML/WindowProxy.h>
  51. #include <LibWeb/HighResolutionTime/Performance.h>
  52. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  53. #include <LibWeb/Infra/Base64.h>
  54. #include <LibWeb/Infra/CharacterTypes.h>
  55. #include <LibWeb/Layout/Viewport.h>
  56. #include <LibWeb/Page/Page.h>
  57. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  58. #include <LibWeb/Selection/Selection.h>
  59. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  60. #include <LibWeb/WebIDL/AbstractOperations.h>
  61. namespace Web::HTML {
  62. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  63. void run_animation_frame_callbacks(DOM::Document& document, double)
  64. {
  65. // FIXME: Bring this closer to the spec.
  66. document.window().animation_frame_callback_driver().run();
  67. }
  68. class IdleCallback : public RefCounted<IdleCallback> {
  69. public:
  70. explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  71. : m_handler(move(handler))
  72. , m_handle(handle)
  73. {
  74. }
  75. ~IdleCallback() = default;
  76. JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  77. u32 handle() const { return m_handle; }
  78. private:
  79. Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  80. u32 m_handle { 0 };
  81. };
  82. WebIDL::ExceptionOr<JS::NonnullGCPtr<Window>> Window::create(JS::Realm& realm)
  83. {
  84. return MUST_OR_THROW_OOM(realm.heap().allocate<Window>(realm, realm));
  85. }
  86. Window::Window(JS::Realm& realm)
  87. : DOM::EventTarget(realm)
  88. {
  89. }
  90. void Window::visit_edges(JS::Cell::Visitor& visitor)
  91. {
  92. Base::visit_edges(visitor);
  93. visitor.visit(m_associated_document.ptr());
  94. visitor.visit(m_current_event.ptr());
  95. visitor.visit(m_performance.ptr());
  96. visitor.visit(m_screen.ptr());
  97. visitor.visit(m_location);
  98. visitor.visit(m_crypto);
  99. visitor.visit(m_navigator);
  100. for (auto& it : m_timers)
  101. visitor.visit(it.value.ptr());
  102. for (auto& plugin_object : m_pdf_viewer_plugin_objects)
  103. visitor.visit(plugin_object);
  104. for (auto& mime_type_object : m_pdf_viewer_mime_type_objects)
  105. visitor.visit(mime_type_object);
  106. }
  107. Window::~Window() = default;
  108. HighResolutionTime::Performance& Window::performance()
  109. {
  110. if (!m_performance)
  111. m_performance = heap().allocate<HighResolutionTime::Performance>(realm(), *this).release_allocated_value_but_fixme_should_propagate_errors();
  112. return *m_performance;
  113. }
  114. CSS::Screen& Window::screen()
  115. {
  116. if (!m_screen)
  117. m_screen = heap().allocate<CSS::Screen>(realm(), *this).release_allocated_value_but_fixme_should_propagate_errors();
  118. return *m_screen;
  119. }
  120. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#normalizing-the-feature-name
  121. static StringView normalize_feature_name(StringView name)
  122. {
  123. // For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
  124. // "screenx"
  125. if (name == "screenx"sv) {
  126. // Return "left".
  127. return "left"sv;
  128. }
  129. // "screeny"
  130. else if (name == "screeny"sv) {
  131. // Return "top".
  132. return "top"sv;
  133. }
  134. // "innerwidth"
  135. else if (name == "innerwidth"sv) {
  136. // Return "width".
  137. return "width"sv;
  138. }
  139. // "innerheight"
  140. else if (name == "innerheight") {
  141. // Return "height".
  142. return "height"sv;
  143. }
  144. // Anything else
  145. else {
  146. // Return name.
  147. return name;
  148. }
  149. }
  150. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-tokenize
  151. static OrderedHashMap<DeprecatedString, DeprecatedString> tokenize_open_features(StringView features)
  152. {
  153. // 1. Let tokenizedFeatures be a new ordered map.
  154. OrderedHashMap<DeprecatedString, DeprecatedString> tokenized_features;
  155. // 2. Let position point at the first code point of features.
  156. GenericLexer lexer(features);
  157. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#feature-separator
  158. auto is_feature_separator = [](auto character) {
  159. return Infra::is_ascii_whitespace(character) || character == '=' || character == ',';
  160. };
  161. // 3. While position is not past the end of features:
  162. while (!lexer.is_eof()) {
  163. // 1. Let name be the empty string.
  164. DeprecatedString name;
  165. // 2. Let value be the empty string.
  166. DeprecatedString value;
  167. // 3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
  168. lexer.ignore_while(is_feature_separator);
  169. // 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.
  170. name = lexer.consume_until(is_feature_separator).to_lowercase_string();
  171. // 5. Set name to the result of normalizing the feature name name.
  172. name = normalize_feature_name(name);
  173. // 6. While position is not past the end of features and the code point at position in features is not U+003D (=):
  174. // 1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
  175. // 2. Advance position by 1.
  176. lexer.ignore_while(Infra::is_ascii_whitespace);
  177. // 7. If the code point at position in features is a feature separator:
  178. // 1. While position is not past the end of features and the code point at position in features is a feature separator:
  179. // 1. If the code point at position in features is U+002C (,), then break.
  180. // 2. Advance position by 1.
  181. lexer.ignore_while([](auto character) { return Infra::is_ascii_whitespace(character) || character == '='; });
  182. // 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.
  183. value = lexer.consume_until(is_feature_separator).to_lowercase_string();
  184. // 8. If name is not the empty string, then set tokenizedFeatures[name] to value.
  185. if (!name.is_empty())
  186. tokenized_features.set(move(name), move(value));
  187. }
  188. // 4. Return tokenizedFeatures.
  189. return tokenized_features;
  190. }
  191. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-parse-boolean
  192. static bool parse_boolean_feature(StringView value)
  193. {
  194. // 1. If value is the empty string, then return true.
  195. if (value.is_empty())
  196. return true;
  197. // 2. If value is "yes", then return true.
  198. if (value == "yes"sv)
  199. return true;
  200. // 3. If value is "true", then return true.
  201. if (value == "true"sv)
  202. return true;
  203. // 4. Let parsed be the result of parsing value as an integer.
  204. auto parsed = value.to_int<i64>();
  205. // 5. If parsed is an error, then set it to 0.
  206. if (!parsed.has_value())
  207. parsed = 0;
  208. // 6. Return false if parsed is 0, and true otherwise.
  209. return *parsed != 0;
  210. }
  211. // https://html.spec.whatwg.org/multipage/window-object.html#popup-window-is-requested
  212. static bool check_if_a_popup_window_is_requested(OrderedHashMap<DeprecatedString, DeprecatedString> const& tokenized_features)
  213. {
  214. // 1. If tokenizedFeatures is empty, then return false.
  215. if (tokenized_features.is_empty())
  216. return false;
  217. // 2. If tokenizedFeatures["popup"] exists, then return the result of parsing tokenizedFeatures["popup"] as a boolean feature.
  218. if (auto popup_feature = tokenized_features.get("popup"sv); popup_feature.has_value())
  219. return parse_boolean_feature(*popup_feature);
  220. // https://html.spec.whatwg.org/multipage/window-object.html#window-feature-is-set
  221. auto check_if_a_window_feature_is_set = [&](StringView feature_name, bool default_value) {
  222. // 1. If tokenizedFeatures[featureName] exists, then return the result of parsing tokenizedFeatures[featureName] as a boolean feature.
  223. if (auto feature = tokenized_features.get(feature_name); feature.has_value())
  224. return parse_boolean_feature(*feature);
  225. // 2. Return defaultValue.
  226. return default_value;
  227. };
  228. // 3. Let location be the result of checking if a window feature is set, given tokenizedFeatures, "location", and false.
  229. auto location = check_if_a_window_feature_is_set("location"sv, false);
  230. // 4. Let toolbar be the result of checking if a window feature is set, given tokenizedFeatures, "toolbar", and false.
  231. auto toolbar = check_if_a_window_feature_is_set("toolbar"sv, false);
  232. // 5. If location and toolbar are both false, then return true.
  233. if (!location && !toolbar)
  234. return true;
  235. // 6. Let menubar be the result of checking if a window feature is set, given tokenizedFeatures, menubar", and false.
  236. auto menubar = check_if_a_window_feature_is_set("menubar"sv, false);
  237. // 7. If menubar is false, then return true.
  238. if (!menubar)
  239. return true;
  240. // 8. Let resizable be the result of checking if a window feature is set, given tokenizedFeatures, "resizable", and true.
  241. auto resizable = check_if_a_window_feature_is_set("resizable"sv, true);
  242. // 9. If resizable is false, then return true.
  243. if (!resizable)
  244. return true;
  245. // 10. Let scrollbars be the result of checking if a window feature is set, given tokenizedFeatures, "scrollbars", and false.
  246. auto scrollbars = check_if_a_window_feature_is_set("scrollbars"sv, false);
  247. // 11. If scrollbars is false, then return true.
  248. if (!scrollbars)
  249. return true;
  250. // 12. Let status be the result of checking if a window feature is set, given tokenizedFeatures, "status", and false.
  251. auto status = check_if_a_window_feature_is_set("status"sv, false);
  252. // 13. If status is false, then return true.
  253. if (!status)
  254. return true;
  255. // 14. Return false.
  256. return false;
  257. }
  258. // FIXME: This is based on the old 'browsing context' concept, which was replaced with 'navigable'
  259. // https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps
  260. WebIDL::ExceptionOr<JS::GCPtr<HTML::WindowProxy>> Window::open_impl(StringView url, StringView target, StringView features)
  261. {
  262. auto& vm = this->vm();
  263. // 1. If the event loop's termination nesting level is nonzero, return null.
  264. if (HTML::main_thread_event_loop().termination_nesting_level() != 0)
  265. return nullptr;
  266. // 2. Let source browsing context be the entry global object's browsing context.
  267. auto* source_browsing_context = verify_cast<Window>(entry_global_object()).browsing_context();
  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 = false;
  275. auto no_referrer = false;
  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(*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(*no_referrer_feature);
  287. // 2. Remove tokenizedFeatures["noreferrer"].
  288. tokenized_features.remove("noreferrer"sv);
  289. }
  290. // 8. If noreferrer is true, then set noopener to true.
  291. if (no_referrer)
  292. no_opener = true;
  293. // 9. Let target browsing context and windowType be the result of applying the rules for choosing a browsing context given target, source browsing context, and noopener.
  294. auto [target_browsing_context, window_type] = source_browsing_context->choose_a_browsing_context(target, no_opener);
  295. // 10. If target browsing context is null, then return null.
  296. if (target_browsing_context == nullptr)
  297. return nullptr;
  298. // 11. If windowType is either "new and unrestricted" or "new with no opener", then:
  299. if (window_type == BrowsingContext::WindowType::NewAndUnrestricted || window_type == BrowsingContext::WindowType::NewWithNoOpener) {
  300. // 1. Set the target browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.
  301. target_browsing_context->set_is_popup(check_if_a_popup_window_is_requested(tokenized_features));
  302. // FIXME: 2. Set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]
  303. // NOTE: While this is not implemented yet, all of observable actions taken by this operation are optional (implementation-defined).
  304. // 3. Let urlRecord be the URL record about:blank.
  305. auto url_record = AK::URL("about:blank"sv);
  306. // 4. If url is not the empty string, then parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "SyntaxError" DOMException.
  307. if (!url.is_empty()) {
  308. url_record = entry_settings_object().parse_url(url);
  309. if (!url_record.is_valid())
  310. return WebIDL::SyntaxError::create(realm(), "URL is not valid");
  311. }
  312. // FIXME: 5. If urlRecord matches about:blank, then perform the URL and history update steps given target browsing context's active document and urlRecord.
  313. // 6. Otherwise:
  314. else {
  315. // 1. Let request be a new request whose URL is urlRecord.
  316. auto request = Fetch::Infrastructure::Request::create(vm);
  317. request->set_url(url_record);
  318. // 2. If noreferrer is true, then set request's referrer to "no-referrer".
  319. if (no_referrer)
  320. request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer);
  321. // 3. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context.
  322. TRY(target_browsing_context->navigate(request, *source_browsing_context, true));
  323. }
  324. }
  325. // 12. Otherwise:
  326. else {
  327. // 1. If url is not the empty string, then:
  328. if (!url.is_empty()) {
  329. // 1. Let urlRecord be the URL record about:blank.
  330. auto url_record = AK::URL("about:blank"sv);
  331. // 2. Parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "SyntaxError" DOMException.
  332. url_record = entry_settings_object().parse_url(url);
  333. if (!url_record.is_valid())
  334. return WebIDL::SyntaxError::create(realm(), "URL is not valid");
  335. // 3. Let request be a new request whose URL is urlRecord.
  336. auto request = Fetch::Infrastructure::Request::create(vm);
  337. request->set_url(url_record);
  338. // 4. If noreferrer is true, then set request's referrer to "noreferrer".
  339. if (no_referrer)
  340. request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer);
  341. // 5. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context.
  342. TRY(target_browsing_context->navigate(request, *source_browsing_context, true));
  343. }
  344. // 2. If noopener is false, then set target browsing context's opener browsing context to source browsing context.
  345. if (!no_opener)
  346. target_browsing_context->set_opener_browsing_context(source_browsing_context);
  347. }
  348. // 13. If noopener is true or windowType is "new with no opener", then return null.
  349. if (no_opener || window_type == BrowsingContext::WindowType::NewWithNoOpener)
  350. return nullptr;
  351. // 14. Return target browsing context's WindowProxy object.
  352. return target_browsing_context->window_proxy();
  353. }
  354. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  355. i32 Window::set_timeout_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  356. {
  357. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  358. }
  359. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  360. i32 Window::set_interval_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  361. {
  362. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  363. }
  364. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  365. void Window::clear_timeout_impl(i32 id)
  366. {
  367. m_timers.remove(id);
  368. }
  369. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  370. void Window::clear_interval_impl(i32 id)
  371. {
  372. m_timers.remove(id);
  373. }
  374. void Window::deallocate_timer_id(Badge<Timer>, i32 id)
  375. {
  376. m_timer_id_allocator.deallocate(id);
  377. }
  378. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  379. i32 Window::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id)
  380. {
  381. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  382. // 2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  383. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  384. // FIXME: 3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.
  385. // 4. If timeout is less than 0, then set timeout to 0.
  386. if (timeout < 0)
  387. timeout = 0;
  388. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  389. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  390. // FIXME: Implement this when step 9.2 is implemented.
  391. // 7. Let initiating script be the active script.
  392. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  393. // 9. Let task be a task that runs the following substeps:
  394. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id] {
  395. // 1. If id does not exist in global's map of active timers, then abort these steps.
  396. if (!m_timers.contains(id))
  397. return;
  398. handler.visit(
  399. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
  400. [&](JS::Handle<WebIDL::CallbackType> callback) {
  401. if (auto result = WebIDL::invoke_callback(*callback, this, arguments); result.is_error())
  402. HTML::report_exception(result, realm());
  403. },
  404. // 3. Otherwise:
  405. [&](DeprecatedString const& source) {
  406. // 1. Assert: handler is a string.
  407. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  408. // 3. Let settings object be global's relevant settings object.
  409. auto& settings_object = associated_document().relevant_settings_object();
  410. // 4. Let base URL be initiating script's base URL.
  411. auto url = associated_document().url();
  412. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  413. // 6. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.
  414. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  415. auto script = HTML::ClassicScript::create(url.basename(), source, settings_object, url);
  416. // 8. Run the classic script script.
  417. (void)script->run();
  418. });
  419. // 4. If id does not exist in global's map of active timers, then abort these steps.
  420. if (!m_timers.contains(id))
  421. return;
  422. switch (repeat) {
  423. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  424. case Repeat::Yes:
  425. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  426. break;
  427. // 6. Otherwise, remove global's map of active timers[id].
  428. case Repeat::No:
  429. m_timers.remove(id);
  430. break;
  431. }
  432. };
  433. // FIXME: 10. Increment nesting level by one.
  434. // FIXME: 11. Set task's timer nesting level to nesting level.
  435. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  436. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  437. HTML::queue_global_task(HTML::Task::Source::TimerTask, *this, move(task));
  438. };
  439. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  440. auto timer = Timer::create(*this, timeout, move(completion_step), id);
  441. m_timers.set(id, timer);
  442. timer->start();
  443. // 14. Return id.
  444. return id;
  445. }
  446. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  447. i32 Window::request_animation_frame_impl(WebIDL::CallbackType& js_callback)
  448. {
  449. return m_animation_frame_callback_driver.add([this, js_callback = JS::make_handle(js_callback)](auto) {
  450. // 3. Invoke callback, passing now as the only argument,
  451. auto result = WebIDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  452. // and if an exception is thrown, report the exception.
  453. if (result.is_error())
  454. HTML::report_exception(result, realm());
  455. });
  456. }
  457. void Window::cancel_animation_frame_impl(i32 id)
  458. {
  459. m_animation_frame_callback_driver.remove(id);
  460. }
  461. void Window::did_set_location_href(Badge<HTML::Location>, AK::URL const& new_href)
  462. {
  463. auto* browsing_context = associated_document().browsing_context();
  464. if (!browsing_context)
  465. return;
  466. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  467. }
  468. void Window::did_call_location_reload(Badge<HTML::Location>)
  469. {
  470. auto* browsing_context = associated_document().browsing_context();
  471. if (!browsing_context)
  472. return;
  473. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  474. }
  475. void Window::did_call_location_replace(Badge<HTML::Location>, DeprecatedString url)
  476. {
  477. auto* browsing_context = associated_document().browsing_context();
  478. if (!browsing_context)
  479. return;
  480. auto new_url = associated_document().parse_url(url);
  481. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  482. }
  483. bool Window::dispatch_event(DOM::Event& event)
  484. {
  485. return DOM::EventDispatcher::dispatch(*this, event, true);
  486. }
  487. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  488. int Window::inner_width() const
  489. {
  490. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  491. // or zero if there is no viewport.
  492. if (auto const* browsing_context = associated_document().browsing_context())
  493. return browsing_context->viewport_rect().width().value();
  494. return 0;
  495. }
  496. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  497. int Window::inner_height() const
  498. {
  499. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  500. // or zero if there is no viewport.
  501. if (auto const* browsing_context = associated_document().browsing_context())
  502. return browsing_context->viewport_rect().height().value();
  503. return 0;
  504. }
  505. Page* Window::page()
  506. {
  507. return associated_document().page();
  508. }
  509. Page const* Window::page() const
  510. {
  511. return associated_document().page();
  512. }
  513. CSS::CSSStyleDeclaration* Window::get_computed_style_impl(DOM::Element& element) const
  514. {
  515. return CSS::ResolvedCSSStyleDeclaration::create(element).release_value_but_fixme_should_propagate_errors().ptr();
  516. }
  517. JS::NonnullGCPtr<CSS::MediaQueryList> Window::match_media_impl(DeprecatedString media)
  518. {
  519. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), media)).release_value_but_fixme_should_propagate_errors();
  520. associated_document().add_media_query_list(*media_query_list);
  521. return media_query_list;
  522. }
  523. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  524. {
  525. // FIXME: Many of these should be dependent on the hardware
  526. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  527. switch (media_feature) {
  528. case CSS::MediaFeatureID::AnyHover:
  529. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  530. case CSS::MediaFeatureID::AnyPointer:
  531. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  532. case CSS::MediaFeatureID::AspectRatio:
  533. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  534. case CSS::MediaFeatureID::Color:
  535. return CSS::MediaFeatureValue(8);
  536. case CSS::MediaFeatureID::ColorGamut:
  537. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  538. case CSS::MediaFeatureID::ColorIndex:
  539. return CSS::MediaFeatureValue(0);
  540. // FIXME: device-aspect-ratio
  541. case CSS::MediaFeatureID::DeviceHeight:
  542. if (auto* page = this->page()) {
  543. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().height().value()));
  544. }
  545. return CSS::MediaFeatureValue(0);
  546. case CSS::MediaFeatureID::DeviceWidth:
  547. if (auto* page = this->page()) {
  548. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().width().value()));
  549. }
  550. return CSS::MediaFeatureValue(0);
  551. case CSS::MediaFeatureID::DisplayMode:
  552. // FIXME: Detect if window is fullscreen
  553. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  554. case CSS::MediaFeatureID::DynamicRange:
  555. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  556. case CSS::MediaFeatureID::EnvironmentBlending:
  557. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  558. case CSS::MediaFeatureID::ForcedColors:
  559. return CSS::MediaFeatureValue(CSS::ValueID::None);
  560. case CSS::MediaFeatureID::Grid:
  561. return CSS::MediaFeatureValue(0);
  562. case CSS::MediaFeatureID::Height:
  563. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  564. case CSS::MediaFeatureID::HorizontalViewportSegments:
  565. return CSS::MediaFeatureValue(1);
  566. case CSS::MediaFeatureID::Hover:
  567. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  568. case CSS::MediaFeatureID::InvertedColors:
  569. return CSS::MediaFeatureValue(CSS::ValueID::None);
  570. case CSS::MediaFeatureID::Monochrome:
  571. return CSS::MediaFeatureValue(0);
  572. case CSS::MediaFeatureID::NavControls:
  573. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  574. case CSS::MediaFeatureID::Orientation:
  575. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  576. case CSS::MediaFeatureID::OverflowBlock:
  577. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  578. case CSS::MediaFeatureID::OverflowInline:
  579. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  580. case CSS::MediaFeatureID::Pointer:
  581. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  582. case CSS::MediaFeatureID::PrefersColorScheme: {
  583. if (auto* page = this->page()) {
  584. switch (page->preferred_color_scheme()) {
  585. case CSS::PreferredColorScheme::Light:
  586. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  587. case CSS::PreferredColorScheme::Dark:
  588. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  589. case CSS::PreferredColorScheme::Auto:
  590. default:
  591. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  592. }
  593. }
  594. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  595. }
  596. case CSS::MediaFeatureID::PrefersContrast:
  597. // FIXME: Make this a preference
  598. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  599. case CSS::MediaFeatureID::PrefersReducedData:
  600. // FIXME: Make this a preference
  601. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  602. case CSS::MediaFeatureID::PrefersReducedMotion:
  603. // FIXME: Make this a preference
  604. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  605. case CSS::MediaFeatureID::PrefersReducedTransparency:
  606. // FIXME: Make this a preference
  607. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  608. // FIXME: resolution
  609. case CSS::MediaFeatureID::Scan:
  610. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  611. case CSS::MediaFeatureID::Scripting:
  612. if (associated_document().is_scripting_enabled())
  613. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  614. return CSS::MediaFeatureValue(CSS::ValueID::None);
  615. case CSS::MediaFeatureID::Update:
  616. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  617. case CSS::MediaFeatureID::VerticalViewportSegments:
  618. return CSS::MediaFeatureValue(1);
  619. case CSS::MediaFeatureID::VideoColorGamut:
  620. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  621. case CSS::MediaFeatureID::VideoDynamicRange:
  622. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  623. case CSS::MediaFeatureID::Width:
  624. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  625. default:
  626. break;
  627. }
  628. return {};
  629. }
  630. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  631. float Window::scroll_x() const
  632. {
  633. if (auto* page = this->page())
  634. return page->top_level_browsing_context().viewport_scroll_offset().x().value();
  635. return 0;
  636. }
  637. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  638. float Window::scroll_y() const
  639. {
  640. if (auto* page = this->page())
  641. return page->top_level_browsing_context().viewport_scroll_offset().y().value();
  642. return 0;
  643. }
  644. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  645. void Window::fire_a_page_transition_event(DeprecatedFlyString const& event_name, bool persisted)
  646. {
  647. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  648. // fire an event named eventName at window, using PageTransitionEvent,
  649. // with the persisted attribute initialized to persisted,
  650. HTML::PageTransitionEventInit event_init {};
  651. event_init.persisted = persisted;
  652. auto event = HTML::PageTransitionEvent::create(associated_document().realm(), String::from_deprecated_string(event_name).release_value_but_fixme_should_propagate_errors(), event_init).release_value_but_fixme_should_propagate_errors();
  653. // ...the cancelable attribute initialized to true,
  654. event->set_cancelable(true);
  655. // the bubbles attribute initialized to true,
  656. event->set_bubbles(true);
  657. // and legacy target override flag set.
  658. dispatch_event(event);
  659. }
  660. // https://html.spec.whatwg.org/#dom-queuemicrotask
  661. void Window::queue_microtask_impl(WebIDL::CallbackType& callback)
  662. {
  663. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  664. HTML::queue_a_microtask(&associated_document(), [this, &callback] {
  665. auto result = WebIDL::invoke_callback(callback, {});
  666. // and if callback throws an exception, report the exception.
  667. if (result.is_error())
  668. HTML::report_exception(result, realm());
  669. });
  670. }
  671. float Window::device_pixel_ratio() const
  672. {
  673. // FIXME: Return 2.0f if we're in HiDPI mode!
  674. return 1.0f;
  675. }
  676. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  677. int Window::screen_x() const
  678. {
  679. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  680. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  681. if (auto* page = this->page())
  682. return page->window_position().x().value();
  683. return 0;
  684. }
  685. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  686. int Window::screen_y() const
  687. {
  688. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  689. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  690. if (auto* page = this->page())
  691. return page->window_position().y().value();
  692. return 0;
  693. }
  694. // https://drafts.csswg.org/cssom-view/#dom-window-outerwidth
  695. int Window::outer_width() const
  696. {
  697. // The outerWidth attribute must return the width of the client window. If there is no client window this attribute must return zero.
  698. if (auto* page = this->page())
  699. return page->window_size().width().value();
  700. return 0;
  701. }
  702. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  703. int Window::outer_height() const
  704. {
  705. // The outerHeight attribute must return the height of the client window. If there is no client window this attribute must return zero.
  706. if (auto* page = this->page())
  707. return page->window_size().height().value();
  708. return 0;
  709. }
  710. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  711. JS::NonnullGCPtr<HTML::Storage> Window::local_storage()
  712. {
  713. // FIXME: Implement according to spec.
  714. static HashMap<Origin, JS::Handle<HTML::Storage>> local_storage_per_origin;
  715. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  716. return *HTML::Storage::create(realm()).release_value_but_fixme_should_propagate_errors();
  717. });
  718. return *storage;
  719. }
  720. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  721. JS::NonnullGCPtr<HTML::Storage> Window::session_storage()
  722. {
  723. // FIXME: Implement according to spec.
  724. static HashMap<Origin, JS::Handle<HTML::Storage>> session_storage_per_origin;
  725. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  726. return *HTML::Storage::create(realm()).release_value_but_fixme_should_propagate_errors();
  727. });
  728. return *storage;
  729. }
  730. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  731. WindowProxy* Window::parent()
  732. {
  733. // 1. Let current be this Window object's browsing context.
  734. auto* current = browsing_context();
  735. // 2. If current is null, then return null.
  736. if (!current)
  737. return nullptr;
  738. // 3. If current is a child browsing context of another browsing context parent,
  739. // then return parent's WindowProxy object.
  740. if (current->parent()) {
  741. return current->parent()->window_proxy();
  742. }
  743. // 4. Assert: current is a top-level browsing context.
  744. VERIFY(current->is_top_level());
  745. // 5. Return current's WindowProxy object.
  746. return current->window_proxy();
  747. }
  748. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  749. WebIDL::ExceptionOr<JS::Value> Window::structured_clone_impl(JS::VM& vm, JS::Value message)
  750. {
  751. auto serialized = TRY(structured_serialize(vm, message));
  752. return MUST(structured_deserialize(vm, serialized, *vm.current_realm(), {}));
  753. }
  754. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  755. DeprecatedString Window::name() const
  756. {
  757. // 1. If this's browsing context is null, then return the empty string.
  758. if (!browsing_context())
  759. return DeprecatedString::empty();
  760. // 2. Return this's browsing context's name.
  761. return browsing_context()->name();
  762. }
  763. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  764. void Window::set_name(DeprecatedString const& name)
  765. {
  766. // 1. If this's browsing context is null, then return.
  767. if (!browsing_context())
  768. return;
  769. // 2. Set this's browsing context's name to the given value.
  770. browsing_context()->set_name(name);
  771. }
  772. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  773. bool Window::has_transient_activation() const
  774. {
  775. // FIXME: Implement this.
  776. return false;
  777. }
  778. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  779. void Window::start_an_idle_period()
  780. {
  781. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  782. // 2. Let pending_list be window's list of idle request callbacks.
  783. auto& pending_list = m_idle_request_callbacks;
  784. // 3. Let run_list be window's list of runnable idle callbacks.
  785. auto& run_list = m_runnable_idle_callbacks;
  786. run_list.extend(pending_list);
  787. // 4. Clear pending_list.
  788. pending_list.clear();
  789. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  790. if (run_list.is_empty())
  791. return;
  792. // 5. Queue a task on the queue associated with the idle-task task source,
  793. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  794. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this] {
  795. invoke_idle_callbacks();
  796. });
  797. }
  798. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  799. void Window::invoke_idle_callbacks()
  800. {
  801. auto& event_loop = main_thread_event_loop();
  802. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  803. // 2. Let now be the current time.
  804. auto now = HighResolutionTime::unsafe_shared_current_time();
  805. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  806. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  807. // 1. Pop the top callback from window's list of runnable idle callbacks.
  808. auto callback = m_runnable_idle_callbacks.take_first();
  809. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  810. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm()).release_value_but_fixme_should_propagate_errors();
  811. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  812. auto result = callback->invoke(deadline_arg);
  813. if (result.is_error())
  814. HTML::report_exception(result, realm());
  815. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  816. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  817. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this] {
  818. invoke_idle_callbacks();
  819. });
  820. }
  821. }
  822. // https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method
  823. u32 Window::request_idle_callback_impl(WebIDL::CallbackType& callback)
  824. {
  825. // 1. Let window be this Window object.
  826. auto& window = *this;
  827. // 2. Increment the window's idle callback identifier by one.
  828. window.m_idle_callback_identifier++;
  829. // 3. Let handle be the current value of window's idle callback identifier.
  830. auto handle = window.m_idle_callback_identifier;
  831. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  832. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  833. return WebIDL::invoke_callback(const_cast<WebIDL::CallbackType&>(*callback), {}, deadline.ptr());
  834. };
  835. window.m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  836. // 5. Return handle and then continue running this algorithm asynchronously.
  837. return handle;
  838. // FIXME: 6. If the timeout property is present in options and has a positive value:
  839. // FIXME: 1. Wait for timeout milliseconds.
  840. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  841. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  842. // 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.
  843. }
  844. // https://w3c.github.io/requestidlecallback/#the-cancelidlecallback-method
  845. void Window::cancel_idle_callback_impl(u32 handle)
  846. {
  847. // 1. Let window be this Window object.
  848. auto& window = *this;
  849. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  850. // that is associated with the value handle.
  851. // 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.
  852. window.m_idle_request_callbacks.remove_first_matching([handle](auto& callback) {
  853. return callback->handle() == handle;
  854. });
  855. window.m_runnable_idle_callbacks.remove_first_matching([handle](auto& callback) {
  856. return callback->handle() == handle;
  857. });
  858. }
  859. void Window::set_associated_document(DOM::Document& document)
  860. {
  861. m_associated_document = &document;
  862. }
  863. void Window::set_current_event(DOM::Event* event)
  864. {
  865. m_current_event = event;
  866. }
  867. HTML::BrowsingContext const* Window::browsing_context() const
  868. {
  869. return m_associated_document->browsing_context();
  870. }
  871. HTML::BrowsingContext* Window::browsing_context()
  872. {
  873. return m_associated_document->browsing_context();
  874. }
  875. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-objects
  876. Vector<JS::NonnullGCPtr<Plugin>> Window::pdf_viewer_plugin_objects()
  877. {
  878. // 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.
  879. // Otherwise, it is a list containing five Plugin objects, whose names are, respectively:
  880. // 0. "PDF Viewer"
  881. // 1. "Chrome PDF Viewer"
  882. // 2. "Chromium PDF Viewer"
  883. // 3. "Microsoft Edge PDF Viewer"
  884. // 4. "WebKit built-in PDF"
  885. // 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
  886. VERIFY(page());
  887. if (!page()->pdf_viewer_supported())
  888. return {};
  889. if (m_pdf_viewer_plugin_objects.is_empty()) {
  890. // FIXME: Propagate errors.
  891. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "PDF Viewer"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  892. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chrome PDF Viewer"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  893. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chromium PDF Viewer"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  894. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Microsoft Edge PDF Viewer"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  895. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "WebKit built-in PDF"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  896. }
  897. return m_pdf_viewer_plugin_objects;
  898. }
  899. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-type-objects
  900. Vector<JS::NonnullGCPtr<MimeType>> Window::pdf_viewer_mime_type_objects()
  901. {
  902. // 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.
  903. // Otherwise, it is a list containing two MimeType objects, whose types are, respectively:
  904. // 0. "application/pdf"
  905. // 1. "text/pdf"
  906. // 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
  907. VERIFY(page());
  908. if (!page()->pdf_viewer_supported())
  909. return {};
  910. if (m_pdf_viewer_mime_type_objects.is_empty()) {
  911. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "application/pdf"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  912. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "text/pdf"_string.release_value_but_fixme_should_propagate_errors()).release_allocated_value_but_fixme_should_propagate_errors());
  913. }
  914. return m_pdf_viewer_mime_type_objects;
  915. }
  916. WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  917. {
  918. auto& realm = this->realm();
  919. add_window_exposed_interfaces(*this);
  920. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WindowPrototype>(realm, "Window"));
  921. m_crypto = MUST_OR_THROW_OOM(heap().allocate<Crypto::Crypto>(realm, realm));
  922. m_location = MUST_OR_THROW_OOM(heap().allocate<Location>(realm, realm));
  923. m_navigator = MUST_OR_THROW_OOM(heap().allocate<Navigator>(realm, realm));
  924. MUST_OR_THROW_OOM(Bindings::WindowGlobalMixin::initialize(realm, *this));
  925. // FIXME: These should be native accessors, not properties
  926. define_native_accessor(realm, "top", top_getter, nullptr, JS::Attribute::Enumerable);
  927. define_native_accessor(realm, "frames", frames_getter, {}, JS::Attribute::Enumerable);
  928. define_native_accessor(realm, "parent", parent_getter, {}, JS::Attribute::Enumerable);
  929. define_native_accessor(realm, "document", document_getter, {}, JS::Attribute::Enumerable);
  930. define_native_accessor(realm, "frameElement", frame_element_getter, {}, JS::Attribute::Enumerable);
  931. define_native_accessor(realm, "name", name_getter, name_setter, JS::Attribute::Enumerable);
  932. define_native_accessor(realm, "history", history_getter, {}, JS::Attribute::Enumerable);
  933. define_native_accessor(realm, "performance", performance_getter, performance_setter, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  934. define_native_accessor(realm, "crypto", crypto_getter, {}, JS::Attribute::Enumerable);
  935. define_native_accessor(realm, "screen", screen_getter, screen_setter, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  936. define_native_accessor(realm, "innerWidth", inner_width_getter, {}, JS::Attribute::Enumerable);
  937. define_native_accessor(realm, "innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable);
  938. define_native_accessor(realm, "devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  939. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  940. define_native_function(realm, "open", open, 0, attr);
  941. define_native_function(realm, "setInterval", set_interval, 1, attr);
  942. define_native_function(realm, "setTimeout", set_timeout, 1, attr);
  943. define_native_function(realm, "clearInterval", clear_interval, 1, attr);
  944. define_native_function(realm, "clearTimeout", clear_timeout, 1, attr);
  945. define_native_function(realm, "requestAnimationFrame", request_animation_frame, 1, attr);
  946. define_native_function(realm, "cancelAnimationFrame", cancel_animation_frame, 1, attr);
  947. define_native_function(realm, "atob", atob, 1, attr);
  948. define_native_function(realm, "btoa", btoa, 1, attr);
  949. define_native_function(realm, "focus", focus, 0, attr);
  950. define_native_function(realm, "queueMicrotask", queue_microtask, 1, attr);
  951. define_native_function(realm, "requestIdleCallback", request_idle_callback, 1, attr);
  952. define_native_function(realm, "cancelIdleCallback", cancel_idle_callback, 1, attr);
  953. define_native_function(realm, "getComputedStyle", get_computed_style, 1, attr);
  954. define_native_function(realm, "matchMedia", match_media, 1, attr);
  955. define_native_function(realm, "getSelection", get_selection, 0, attr);
  956. define_native_function(realm, "structuredClone", structured_clone, 1, attr);
  957. define_native_function(realm, "fetch", Bindings::fetch, 1, attr);
  958. // FIXME: These properties should be [Replaceable] according to the spec, but [Writable+Configurable] is the closest we have.
  959. define_native_accessor(realm, "scrollX", scroll_x_getter, {}, attr);
  960. define_native_accessor(realm, "pageXOffset", scroll_x_getter, {}, attr);
  961. define_native_accessor(realm, "scrollY", scroll_y_getter, {}, attr);
  962. define_native_accessor(realm, "pageYOffset", scroll_y_getter, {}, attr);
  963. define_native_accessor(realm, "length", length_getter, {}, attr);
  964. define_native_function(realm, "scroll", scroll, 2, attr);
  965. define_native_function(realm, "scrollTo", scroll, 2, attr);
  966. define_native_function(realm, "scrollBy", scroll_by, 2, attr);
  967. define_native_accessor(realm, "screenX", screen_x_getter, {}, attr);
  968. define_native_accessor(realm, "screenY", screen_y_getter, {}, attr);
  969. define_native_accessor(realm, "screenLeft", screen_left_getter, {}, attr);
  970. define_native_accessor(realm, "screenTop", screen_top_getter, {}, attr);
  971. define_native_accessor(realm, "outerWidth", outer_width_getter, {}, attr);
  972. define_native_accessor(realm, "outerHeight", outer_height_getter, {}, attr);
  973. define_direct_property("CSS", MUST_OR_THROW_OOM(heap().allocate<Bindings::CSSNamespace>(realm, realm)), 0);
  974. define_native_accessor(realm, "localStorage", local_storage_getter, {}, attr);
  975. define_native_accessor(realm, "sessionStorage", session_storage_getter, {}, attr);
  976. define_native_accessor(realm, "origin", origin_getter, {}, attr);
  977. define_native_accessor(realm, "isSecureContext", is_secure_context_getter, {}, attr);
  978. // Legacy
  979. define_native_accessor(realm, "event", event_getter, event_setter, JS::Attribute::Enumerable);
  980. // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable.
  981. define_native_accessor(realm, "location", location_getter, location_setter, JS::Attribute::Enumerable);
  982. // WebAssembly "namespace"
  983. define_direct_property("WebAssembly", MUST_OR_THROW_OOM(heap().allocate<Bindings::WebAssemblyObject>(realm, realm)), JS::Attribute::Enumerable | JS::Attribute::Configurable);
  984. return {};
  985. }
  986. HTML::Origin Window::origin() const
  987. {
  988. return associated_document().origin();
  989. }
  990. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  991. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  992. {
  993. // 1. Return ? SetImmutablePrototype(O, V).
  994. return set_immutable_prototype(prototype);
  995. }
  996. static JS::ThrowCompletionOr<HTML::Window*> impl_from(JS::VM& vm)
  997. {
  998. // Since this is a non built-in function we must treat it as non-strict mode
  999. // this means that a nullish this_value should be converted to the
  1000. // global_object. Generally this does not matter as we try to convert the
  1001. // this_value to a specific object type in the bindings. But since window is
  1002. // the global object we make an exception here.
  1003. // This allows calls like `setTimeout(f, 10)` to work.
  1004. auto this_value = vm.this_value();
  1005. if (this_value.is_nullish())
  1006. this_value = &vm.current_realm()->global_object();
  1007. auto* this_object = MUST(this_value.to_object(vm));
  1008. if (is<WindowProxy>(*this_object))
  1009. return static_cast<WindowProxy*>(this_object)->window().ptr();
  1010. if (is<Window>(*this_object))
  1011. return static_cast<Window*>(this_object);
  1012. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Window");
  1013. }
  1014. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  1015. JS::NonnullGCPtr<WindowProxy> Window::window() const
  1016. {
  1017. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  1018. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  1019. }
  1020. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  1021. JS::NonnullGCPtr<WindowProxy> Window::self() const
  1022. {
  1023. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  1024. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  1025. }
  1026. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  1027. JS::NonnullGCPtr<Navigator> Window::navigator() const
  1028. {
  1029. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  1030. return *m_navigator;
  1031. }
  1032. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  1033. void Window::alert(String const& message)
  1034. {
  1035. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  1036. // Note: This method is defined using two overloads, instead of using an optional argument,
  1037. // for historical reasons. The practical impact of this is that alert(undefined) is
  1038. // treated as alert("undefined"), but alert() is treated as alert("").
  1039. // FIXME: Make this fully spec compliant.
  1040. if (auto* page = this->page())
  1041. page->did_request_alert(message.to_deprecated_string());
  1042. }
  1043. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  1044. bool Window::confirm(Optional<String> const& message)
  1045. {
  1046. // FIXME: Make this fully spec compliant.
  1047. // NOTE: `message` has an IDL-provided default value and is never empty.
  1048. if (auto* page = this->page())
  1049. return page->did_request_confirm(message->to_deprecated_string());
  1050. return false;
  1051. }
  1052. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  1053. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  1054. {
  1055. // FIXME: Make this fully spec compliant.
  1056. if (auto* page = this->page()) {
  1057. auto response = page->did_request_prompt(message->to_deprecated_string(), default_->to_deprecated_string());
  1058. if (response.is_null())
  1059. return {};
  1060. return String::from_deprecated_string(response).release_value_but_fixme_should_propagate_errors();
  1061. }
  1062. return {};
  1063. }
  1064. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  1065. void Window::post_message(JS::Value message, String const&)
  1066. {
  1067. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  1068. // have serialization and deserialization of messages.
  1069. HTML::queue_global_task(HTML::Task::Source::PostedMessage, *this, [this, message] {
  1070. HTML::MessageEventInit event_init {};
  1071. event_init.data = message;
  1072. event_init.origin = "<origin>"_string.release_value_but_fixme_should_propagate_errors();
  1073. dispatch_event(HTML::MessageEvent::create(realm(), String::from_deprecated_string(HTML::EventNames::message).release_value_but_fixme_should_propagate_errors(), event_init).release_value_but_fixme_should_propagate_errors());
  1074. });
  1075. }
  1076. JS_DEFINE_NATIVE_FUNCTION(Window::open)
  1077. {
  1078. auto* impl = TRY(impl_from(vm));
  1079. // optional USVString url = ""
  1080. DeprecatedString url = "";
  1081. if (!vm.argument(0).is_undefined())
  1082. url = TRY(vm.argument(0).to_deprecated_string(vm));
  1083. // optional DOMString target = "_blank"
  1084. DeprecatedString target = "_blank";
  1085. if (!vm.argument(1).is_undefined())
  1086. target = TRY(vm.argument(1).to_deprecated_string(vm));
  1087. // optional [LegacyNullToEmptyString] DOMString features = "")
  1088. DeprecatedString features = "";
  1089. if (!vm.argument(2).is_nullish())
  1090. features = TRY(vm.argument(2).to_deprecated_string(vm));
  1091. return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->open_impl(url, target, features); }));
  1092. }
  1093. static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler)
  1094. {
  1095. if (handler.is_function())
  1096. return JS::make_handle(vm.heap().allocate_without_realm<WebIDL::CallbackType>(handler.as_function(), HTML::incumbent_settings_object()));
  1097. return TRY(handler.to_deprecated_string(vm));
  1098. }
  1099. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  1100. JS_DEFINE_NATIVE_FUNCTION(Window::set_timeout)
  1101. {
  1102. auto* impl = TRY(impl_from(vm));
  1103. if (!vm.argument_count())
  1104. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
  1105. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1106. i32 timeout = 0;
  1107. if (vm.argument_count() >= 2)
  1108. timeout = TRY(vm.argument(1).to_i32(vm));
  1109. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1110. for (size_t i = 2; i < vm.argument_count(); ++i)
  1111. arguments.append(vm.argument(i));
  1112. auto id = impl->set_timeout_impl(move(handler), timeout, move(arguments));
  1113. return JS::Value(id);
  1114. }
  1115. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  1116. JS_DEFINE_NATIVE_FUNCTION(Window::set_interval)
  1117. {
  1118. auto* impl = TRY(impl_from(vm));
  1119. if (!vm.argument_count())
  1120. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
  1121. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1122. i32 timeout = 0;
  1123. if (vm.argument_count() >= 2)
  1124. timeout = TRY(vm.argument(1).to_i32(vm));
  1125. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1126. for (size_t i = 2; i < vm.argument_count(); ++i)
  1127. arguments.append(vm.argument(i));
  1128. auto id = impl->set_interval_impl(move(handler), timeout, move(arguments));
  1129. return JS::Value(id);
  1130. }
  1131. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  1132. JS_DEFINE_NATIVE_FUNCTION(Window::clear_timeout)
  1133. {
  1134. auto* impl = TRY(impl_from(vm));
  1135. i32 id = 0;
  1136. if (vm.argument_count())
  1137. id = TRY(vm.argument(0).to_i32(vm));
  1138. impl->clear_timeout_impl(id);
  1139. return JS::js_undefined();
  1140. }
  1141. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  1142. JS_DEFINE_NATIVE_FUNCTION(Window::clear_interval)
  1143. {
  1144. auto* impl = TRY(impl_from(vm));
  1145. i32 id = 0;
  1146. if (vm.argument_count())
  1147. id = TRY(vm.argument(0).to_i32(vm));
  1148. impl->clear_interval_impl(id);
  1149. return JS::js_undefined();
  1150. }
  1151. JS_DEFINE_NATIVE_FUNCTION(Window::request_animation_frame)
  1152. {
  1153. auto* impl = TRY(impl_from(vm));
  1154. if (!vm.argument_count())
  1155. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "requestAnimationFrame");
  1156. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1157. if (!callback_object->is_function())
  1158. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1159. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1160. return JS::Value(impl->request_animation_frame_impl(*callback));
  1161. }
  1162. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_animation_frame)
  1163. {
  1164. auto* impl = TRY(impl_from(vm));
  1165. if (!vm.argument_count())
  1166. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelAnimationFrame");
  1167. auto id = TRY(vm.argument(0).to_i32(vm));
  1168. impl->cancel_animation_frame_impl(id);
  1169. return JS::js_undefined();
  1170. }
  1171. JS_DEFINE_NATIVE_FUNCTION(Window::queue_microtask)
  1172. {
  1173. auto* impl = TRY(impl_from(vm));
  1174. if (!vm.argument_count())
  1175. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "queueMicrotask");
  1176. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1177. if (!callback_object->is_function())
  1178. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1179. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1180. impl->queue_microtask_impl(*callback);
  1181. return JS::js_undefined();
  1182. }
  1183. JS_DEFINE_NATIVE_FUNCTION(Window::request_idle_callback)
  1184. {
  1185. auto* impl = TRY(impl_from(vm));
  1186. if (!vm.argument_count())
  1187. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "requestIdleCallback");
  1188. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1189. if (!callback_object->is_function())
  1190. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1191. // FIXME: accept options object
  1192. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1193. return JS::Value(impl->request_idle_callback_impl(*callback));
  1194. }
  1195. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_idle_callback)
  1196. {
  1197. auto* impl = TRY(impl_from(vm));
  1198. if (!vm.argument_count())
  1199. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelIdleCallback");
  1200. auto id = TRY(vm.argument(0).to_u32(vm));
  1201. impl->cancel_idle_callback_impl(id);
  1202. return JS::js_undefined();
  1203. }
  1204. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob-dev
  1205. JS_DEFINE_NATIVE_FUNCTION(Window::atob)
  1206. {
  1207. if (!vm.argument_count())
  1208. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "atob");
  1209. auto deprecated_string = TRY(vm.argument(0).to_deprecated_string(vm));
  1210. auto string = String::from_utf8(deprecated_string).release_value_but_fixme_should_propagate_errors();
  1211. // must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF
  1212. for (auto code_point : string.code_points()) {
  1213. if (code_point > 0x00FF)
  1214. return throw_completion(WebIDL::InvalidCharacterError::create(*vm.current_realm(), "Data contains characters outside the range U+0000 and U+00FF"));
  1215. }
  1216. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data
  1217. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  1218. auto decoded = Infra::decode_forgiving_base64(StringView(deprecated_string));
  1219. if (decoded.is_error())
  1220. return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidFormat, "Base64");
  1221. // The bytes object might contain bytes greater than 128, encode them in UTF8
  1222. // NOTE: Any 8-bit encoding -> utf-8 decoder will work for this
  1223. auto text_decoder = TextCodec::decoder_for("windows-1252"sv);
  1224. VERIFY(text_decoder.has_value());
  1225. auto text = TRY_OR_THROW_OOM(vm, text_decoder->to_utf8(decoded.release_value()));
  1226. return JS::PrimitiveString::create(vm, text);
  1227. }
  1228. JS_DEFINE_NATIVE_FUNCTION(Window::btoa)
  1229. {
  1230. if (!vm.argument_count())
  1231. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "btoa");
  1232. auto string = TRY(vm.argument(0).to_deprecated_string(vm));
  1233. Vector<u8> byte_string;
  1234. byte_string.ensure_capacity(string.length());
  1235. for (u32 code_point : Utf8View(string)) {
  1236. if (code_point > 0xff)
  1237. return throw_completion(WebIDL::InvalidCharacterError::create(*vm.current_realm(), "Data contains characters outside the range U+0000 and U+00FF"));
  1238. byte_string.append(code_point);
  1239. }
  1240. auto encoded = MUST(encode_base64(byte_string.span()));
  1241. return JS::PrimitiveString::create(vm, encoded.to_deprecated_string());
  1242. }
  1243. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  1244. JS_DEFINE_NATIVE_FUNCTION(Window::focus)
  1245. {
  1246. auto* impl = TRY(impl_from(vm));
  1247. // 1. Let current be this Window object's browsing context.
  1248. auto* current = impl->browsing_context();
  1249. // 2. If current is null, then return.
  1250. if (!current)
  1251. return JS::js_undefined();
  1252. // 3. Run the focusing steps with current.
  1253. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  1254. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  1255. run_focusing_steps(current->active_document());
  1256. // FIXME: 4. If current is a top-level browsing context, user agents are encouraged to trigger some sort of notification to indicate to the user that the page is attempting to gain focus.
  1257. return JS::js_undefined();
  1258. }
  1259. // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts
  1260. JS::ThrowCompletionOr<size_t> Window::document_tree_child_browsing_context_count() const
  1261. {
  1262. // 1. If W's browsing context is null, then return 0.
  1263. auto* this_browsing_context = associated_document().browsing_context();
  1264. if (!this_browsing_context)
  1265. return 0;
  1266. // 2. Return the number of document-tree child browsing contexts of W's browsing context.
  1267. return this_browsing_context->document_tree_child_browsing_context_count();
  1268. }
  1269. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  1270. JS_DEFINE_NATIVE_FUNCTION(Window::length_getter)
  1271. {
  1272. auto* impl = TRY(impl_from(vm));
  1273. // The length getter steps are to return the number of document-tree child browsing contexts of this.
  1274. return TRY(impl->document_tree_child_browsing_context_count());
  1275. }
  1276. // https://html.spec.whatwg.org/multipage/browsers.html#dom-top
  1277. JS_DEFINE_NATIVE_FUNCTION(Window::top_getter)
  1278. {
  1279. auto* impl = TRY(impl_from(vm));
  1280. // 1. If this Window object's browsing context is null, then return null.
  1281. auto* browsing_context = impl->browsing_context();
  1282. if (!browsing_context)
  1283. return JS::js_null();
  1284. // 2. Return this Window object's browsing context's top-level browsing context's WindowProxy object.
  1285. return browsing_context->top_level_browsing_context().window_proxy();
  1286. }
  1287. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  1288. JS_DEFINE_NATIVE_FUNCTION(Window::frames_getter)
  1289. {
  1290. auto* impl = TRY(impl_from(vm));
  1291. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  1292. return &relevant_realm(*impl).global_environment().global_this_value();
  1293. }
  1294. JS_DEFINE_NATIVE_FUNCTION(Window::parent_getter)
  1295. {
  1296. auto* impl = TRY(impl_from(vm));
  1297. auto* parent = impl->parent();
  1298. if (!parent)
  1299. return JS::js_null();
  1300. return parent;
  1301. }
  1302. JS_DEFINE_NATIVE_FUNCTION(Window::document_getter)
  1303. {
  1304. auto* impl = TRY(impl_from(vm));
  1305. return &impl->associated_document();
  1306. }
  1307. // https://html.spec.whatwg.org/multipage/browsers.html#dom-frameelement
  1308. JS_DEFINE_NATIVE_FUNCTION(Window::frame_element_getter)
  1309. {
  1310. auto* impl = TRY(impl_from(vm));
  1311. // 1. Let current be this Window object's browsing context.
  1312. auto* current = impl->browsing_context();
  1313. // 2. If current is null, then return null.
  1314. if (!current)
  1315. return JS::js_null();
  1316. // 3. Let container be current's container.
  1317. auto* container = current->container();
  1318. // 4. If container is null, then return null.
  1319. if (!container)
  1320. return JS::js_null();
  1321. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  1322. if (!container->document().origin().is_same_origin(current_settings_object().origin()))
  1323. return JS::js_null();
  1324. // 6. Return container.
  1325. return container;
  1326. }
  1327. JS_DEFINE_NATIVE_FUNCTION(Window::performance_getter)
  1328. {
  1329. auto* impl = TRY(impl_from(vm));
  1330. return &impl->performance();
  1331. }
  1332. JS_DEFINE_NATIVE_FUNCTION(Window::performance_setter)
  1333. {
  1334. // https://webidl.spec.whatwg.org/#dfn-attribute-setter
  1335. // 4.1. If no arguments were passed, then throw a TypeError.
  1336. if (vm.argument_count() == 0)
  1337. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "set performance");
  1338. auto* impl = TRY(impl_from(vm));
  1339. // 5. If attribute is declared with the [Replaceable] extended attribute, then:
  1340. // 1. Perform ? CreateDataProperty(esValue, id, V).
  1341. TRY(impl->create_data_property("performance", vm.argument(0)));
  1342. // 2. Return undefined.
  1343. return JS::js_undefined();
  1344. }
  1345. JS_DEFINE_NATIVE_FUNCTION(Window::screen_getter)
  1346. {
  1347. auto* impl = TRY(impl_from(vm));
  1348. return &impl->screen();
  1349. }
  1350. JS_DEFINE_NATIVE_FUNCTION(Window::screen_setter)
  1351. {
  1352. REPLACEABLE_PROPERTY_SETTER(Window, screen);
  1353. }
  1354. JS_DEFINE_NATIVE_FUNCTION(Window::event_getter)
  1355. {
  1356. auto* impl = TRY(impl_from(vm));
  1357. if (!impl->current_event())
  1358. return JS::js_undefined();
  1359. return impl->current_event();
  1360. }
  1361. JS_DEFINE_NATIVE_FUNCTION(Window::event_setter)
  1362. {
  1363. REPLACEABLE_PROPERTY_SETTER(Window, event);
  1364. }
  1365. JS_DEFINE_NATIVE_FUNCTION(Window::location_getter)
  1366. {
  1367. auto* impl = TRY(impl_from(vm));
  1368. return impl->m_location;
  1369. }
  1370. JS_DEFINE_NATIVE_FUNCTION(Window::location_setter)
  1371. {
  1372. auto* impl = TRY(impl_from(vm));
  1373. TRY(impl->m_location->set(JS::PropertyKey("href"), vm.argument(0), JS::Object::ShouldThrowExceptions::Yes));
  1374. return JS::js_undefined();
  1375. }
  1376. JS_DEFINE_NATIVE_FUNCTION(Window::crypto_getter)
  1377. {
  1378. auto* impl = TRY(impl_from(vm));
  1379. return &impl->crypto();
  1380. }
  1381. JS_DEFINE_NATIVE_FUNCTION(Window::inner_width_getter)
  1382. {
  1383. auto* impl = TRY(impl_from(vm));
  1384. return JS::Value(impl->inner_width());
  1385. }
  1386. JS_DEFINE_NATIVE_FUNCTION(Window::inner_height_getter)
  1387. {
  1388. auto* impl = TRY(impl_from(vm));
  1389. return JS::Value(impl->inner_height());
  1390. }
  1391. JS_DEFINE_NATIVE_FUNCTION(Window::device_pixel_ratio_getter)
  1392. {
  1393. auto* impl = TRY(impl_from(vm));
  1394. return JS::Value(impl->device_pixel_ratio());
  1395. }
  1396. JS_DEFINE_NATIVE_FUNCTION(Window::get_computed_style)
  1397. {
  1398. auto* impl = TRY(impl_from(vm));
  1399. auto* object = TRY(vm.argument(0).to_object(vm));
  1400. if (!is<DOM::Element>(object))
  1401. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "DOM element");
  1402. return impl->get_computed_style_impl(*static_cast<DOM::Element*>(object));
  1403. }
  1404. // https://w3c.github.io/selection-api/#dom-window-getselection
  1405. JS_DEFINE_NATIVE_FUNCTION(Window::get_selection)
  1406. {
  1407. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1408. auto* impl = TRY(impl_from(vm));
  1409. return impl->associated_document().get_selection();
  1410. }
  1411. JS_DEFINE_NATIVE_FUNCTION(Window::match_media)
  1412. {
  1413. auto* impl = TRY(impl_from(vm));
  1414. auto media = TRY(vm.argument(0).to_deprecated_string(vm));
  1415. return impl->match_media_impl(move(media));
  1416. }
  1417. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  1418. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_x_getter)
  1419. {
  1420. auto* impl = TRY(impl_from(vm));
  1421. return JS::Value(impl->scroll_x());
  1422. }
  1423. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  1424. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_y_getter)
  1425. {
  1426. auto* impl = TRY(impl_from(vm));
  1427. return JS::Value(impl->scroll_y());
  1428. }
  1429. enum class ScrollBehavior {
  1430. Auto,
  1431. Smooth
  1432. };
  1433. // https://www.w3.org/TR/cssom-view/#perform-a-scroll
  1434. static void perform_a_scroll(Page& page, double x, double y, ScrollBehavior)
  1435. {
  1436. // FIXME: Stop any existing smooth-scrolls
  1437. // FIXME: Implement smooth-scroll
  1438. page.client().page_did_request_scroll_to({ x, y });
  1439. }
  1440. // https://www.w3.org/TR/cssom-view/#dom-window-scroll
  1441. JS_DEFINE_NATIVE_FUNCTION(Window::scroll)
  1442. {
  1443. auto* impl = TRY(impl_from(vm));
  1444. if (!impl->page())
  1445. return JS::js_undefined();
  1446. auto& page = *impl->page();
  1447. auto viewport_rect = page.top_level_browsing_context().viewport_rect().to_type<float>();
  1448. auto x_value = JS::Value(viewport_rect.x());
  1449. auto y_value = JS::Value(viewport_rect.y());
  1450. DeprecatedString behavior_string = "auto";
  1451. if (vm.argument_count() == 1) {
  1452. auto* options = TRY(vm.argument(0).to_object(vm));
  1453. auto left = TRY(options->get("left"));
  1454. if (!left.is_undefined())
  1455. x_value = left;
  1456. auto top = TRY(options->get("top"));
  1457. if (!top.is_undefined())
  1458. y_value = top;
  1459. auto behavior_string_value = TRY(options->get("behavior"));
  1460. if (!behavior_string_value.is_undefined())
  1461. behavior_string = TRY(behavior_string_value.to_deprecated_string(vm));
  1462. if (behavior_string != "smooth" && behavior_string != "auto")
  1463. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'"sv);
  1464. } else if (vm.argument_count() >= 2) {
  1465. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1466. x_value = vm.argument(0);
  1467. y_value = vm.argument(1);
  1468. }
  1469. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1470. double x = TRY(x_value.to_double(vm));
  1471. x = JS::Value(x).is_finite_number() ? x : 0.0;
  1472. double y = TRY(y_value.to_double(vm));
  1473. y = JS::Value(y).is_finite_number() ? y : 0.0;
  1474. // FIXME: Are we calculating the viewport in the way this function expects?
  1475. // FIXME: Handle overflow-directions other than top-left to bottom-right
  1476. perform_a_scroll(page, x, y, behavior);
  1477. return JS::js_undefined();
  1478. }
  1479. // https://www.w3.org/TR/cssom-view/#dom-window-scrollby
  1480. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_by)
  1481. {
  1482. auto& realm = *vm.current_realm();
  1483. auto* impl = TRY(impl_from(vm));
  1484. if (!impl->page())
  1485. return JS::js_undefined();
  1486. auto& page = *impl->page();
  1487. JS::Object* options = nullptr;
  1488. if (vm.argument_count() == 0) {
  1489. options = JS::Object::create(realm, nullptr);
  1490. } else if (vm.argument_count() == 1) {
  1491. options = TRY(vm.argument(0).to_object(vm));
  1492. } else if (vm.argument_count() >= 2) {
  1493. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1494. options = JS::Object::create(realm, nullptr);
  1495. MUST(options->set("left", vm.argument(0), ShouldThrowExceptions::No));
  1496. MUST(options->set("top", vm.argument(1), ShouldThrowExceptions::No));
  1497. MUST(options->set("behavior", MUST_OR_THROW_OOM(JS::PrimitiveString::create(vm, "auto"sv)), ShouldThrowExceptions::No));
  1498. }
  1499. auto left_value = TRY(options->get("left"));
  1500. auto left = TRY(left_value.to_double(vm));
  1501. auto top_value = TRY(options->get("top"));
  1502. auto top = TRY(top_value.to_double(vm));
  1503. left = JS::Value(left).is_finite_number() ? left : 0.0;
  1504. top = JS::Value(top).is_finite_number() ? top : 0.0;
  1505. auto current_scroll_position = page.top_level_browsing_context().viewport_scroll_offset().to_type<float>();
  1506. left = left + static_cast<double>(current_scroll_position.x());
  1507. top = top + static_cast<double>(current_scroll_position.y());
  1508. auto behavior_string_value = TRY(options->get("behavior"));
  1509. auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY(behavior_string_value.to_deprecated_string(vm));
  1510. if (behavior_string != "smooth" && behavior_string != "auto")
  1511. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'"sv);
  1512. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1513. // FIXME: Spec wants us to call scroll(options) here.
  1514. // The only difference is that would invoke the viewport calculations that scroll()
  1515. // is not actually doing yet, so this is the same for now.
  1516. perform_a_scroll(page, left, top, behavior);
  1517. return JS::js_undefined();
  1518. }
  1519. JS_DEFINE_NATIVE_FUNCTION(Window::history_getter)
  1520. {
  1521. auto* impl = TRY(impl_from(vm));
  1522. return impl->associated_document().history();
  1523. }
  1524. JS_DEFINE_NATIVE_FUNCTION(Window::screen_left_getter)
  1525. {
  1526. auto* impl = TRY(impl_from(vm));
  1527. return JS::Value(impl->screen_x());
  1528. }
  1529. JS_DEFINE_NATIVE_FUNCTION(Window::screen_top_getter)
  1530. {
  1531. auto* impl = TRY(impl_from(vm));
  1532. return JS::Value(impl->screen_y());
  1533. }
  1534. JS_DEFINE_NATIVE_FUNCTION(Window::screen_x_getter)
  1535. {
  1536. auto* impl = TRY(impl_from(vm));
  1537. return JS::Value(impl->screen_x());
  1538. }
  1539. JS_DEFINE_NATIVE_FUNCTION(Window::screen_y_getter)
  1540. {
  1541. auto* impl = TRY(impl_from(vm));
  1542. return JS::Value(impl->screen_y());
  1543. }
  1544. JS_DEFINE_NATIVE_FUNCTION(Window::outer_width_getter)
  1545. {
  1546. auto* impl = TRY(impl_from(vm));
  1547. return JS::Value(impl->outer_width());
  1548. }
  1549. JS_DEFINE_NATIVE_FUNCTION(Window::outer_height_getter)
  1550. {
  1551. auto* impl = TRY(impl_from(vm));
  1552. return JS::Value(impl->outer_height());
  1553. }
  1554. JS_DEFINE_NATIVE_FUNCTION(Window::structured_clone)
  1555. {
  1556. auto* impl = TRY(impl_from(vm));
  1557. return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] {
  1558. return impl->structured_clone_impl(vm, vm.argument(0));
  1559. }));
  1560. }
  1561. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  1562. JS_DEFINE_NATIVE_FUNCTION(Window::origin_getter)
  1563. {
  1564. auto* impl = TRY(impl_from(vm));
  1565. return JS::PrimitiveString::create(vm, impl->associated_document().origin().serialize());
  1566. }
  1567. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  1568. JS_DEFINE_NATIVE_FUNCTION(Window::is_secure_context_getter)
  1569. {
  1570. auto* impl = TRY(impl_from(vm));
  1571. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  1572. return JS::Value(is_secure_context(impl->associated_document().relevant_settings_object()));
  1573. }
  1574. JS_DEFINE_NATIVE_FUNCTION(Window::local_storage_getter)
  1575. {
  1576. auto* impl = TRY(impl_from(vm));
  1577. return impl->local_storage();
  1578. }
  1579. JS_DEFINE_NATIVE_FUNCTION(Window::session_storage_getter)
  1580. {
  1581. auto* impl = TRY(impl_from(vm));
  1582. return impl->session_storage();
  1583. }
  1584. JS_DEFINE_NATIVE_FUNCTION(Window::name_getter)
  1585. {
  1586. auto* impl = TRY(impl_from(vm));
  1587. return JS::PrimitiveString::create(vm, impl->name());
  1588. }
  1589. JS_DEFINE_NATIVE_FUNCTION(Window::name_setter)
  1590. {
  1591. auto* impl = TRY(impl_from(vm));
  1592. impl->set_name(TRY(vm.argument(0).to_deprecated_string(vm)));
  1593. return JS::js_undefined();
  1594. }
  1595. }