Window.cpp 80 KB

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