Window.cpp 68 KB

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