Window.cpp 74 KB

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