Window.cpp 76 KB

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