Window.cpp 77 KB

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