WindowObject.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Base64.h>
  8. #include <AK/String.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/Error.h>
  12. #include <LibJS/Runtime/FunctionObject.h>
  13. #include <LibJS/Runtime/Shape.h>
  14. #include <LibTextCodec/Decoder.h>
  15. #include <LibWeb/Bindings/CSSNamespace.h>
  16. #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
  17. #include <LibWeb/Bindings/CryptoWrapper.h>
  18. #include <LibWeb/Bindings/DocumentWrapper.h>
  19. #include <LibWeb/Bindings/ElementWrapper.h>
  20. #include <LibWeb/Bindings/EventTargetConstructor.h>
  21. #include <LibWeb/Bindings/EventTargetPrototype.h>
  22. #include <LibWeb/Bindings/EventWrapper.h>
  23. #include <LibWeb/Bindings/EventWrapperFactory.h>
  24. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  25. #include <LibWeb/Bindings/HistoryWrapper.h>
  26. #include <LibWeb/Bindings/LocationObject.h>
  27. #include <LibWeb/Bindings/MediaQueryListWrapper.h>
  28. #include <LibWeb/Bindings/NavigatorObject.h>
  29. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  30. #include <LibWeb/Bindings/PerformanceWrapper.h>
  31. #include <LibWeb/Bindings/Replaceable.h>
  32. #include <LibWeb/Bindings/ScreenWrapper.h>
  33. #include <LibWeb/Bindings/SelectionWrapper.h>
  34. #include <LibWeb/Bindings/WindowObject.h>
  35. #include <LibWeb/Bindings/WindowObjectHelper.h>
  36. #include <LibWeb/Crypto/Crypto.h>
  37. #include <LibWeb/DOM/Document.h>
  38. #include <LibWeb/DOM/Event.h>
  39. #include <LibWeb/DOM/Window.h>
  40. #include <LibWeb/HTML/BrowsingContext.h>
  41. #include <LibWeb/HTML/EventHandler.h>
  42. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  43. #include <LibWeb/HTML/Scripting/Environments.h>
  44. #include <LibWeb/Origin.h>
  45. #include <LibWeb/Page/Page.h>
  46. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  47. namespace Web::Bindings {
  48. WindowObject::WindowObject(DOM::Window& impl)
  49. : m_impl(impl)
  50. {
  51. impl.set_wrapper({}, *this);
  52. }
  53. void WindowObject::initialize_global_object()
  54. {
  55. Base::initialize_global_object();
  56. Object::set_prototype(&ensure_web_prototype<EventTargetPrototype>("EventTarget"));
  57. // FIXME: These should be native accessors, not properties
  58. define_direct_property("window", this, JS::Attribute::Enumerable);
  59. define_direct_property("frames", this, JS::Attribute::Enumerable);
  60. define_direct_property("self", this, JS::Attribute::Enumerable);
  61. define_native_accessor("top", top_getter, nullptr, JS::Attribute::Enumerable);
  62. define_native_accessor("parent", parent_getter, {}, JS::Attribute::Enumerable);
  63. define_native_accessor("document", document_getter, {}, JS::Attribute::Enumerable);
  64. define_native_accessor("history", history_getter, {}, JS::Attribute::Enumerable);
  65. define_native_accessor("performance", performance_getter, {}, JS::Attribute::Enumerable);
  66. define_native_accessor("crypto", crypto_getter, {}, JS::Attribute::Enumerable);
  67. define_native_accessor("screen", screen_getter, {}, JS::Attribute::Enumerable);
  68. define_native_accessor("innerWidth", inner_width_getter, {}, JS::Attribute::Enumerable);
  69. define_native_accessor("innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable);
  70. define_native_accessor("devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  71. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  72. define_native_function("alert", alert, 0, attr);
  73. define_native_function("confirm", confirm, 0, attr);
  74. define_native_function("prompt", prompt, 0, attr);
  75. define_native_function("setInterval", set_interval, 1, attr);
  76. define_native_function("setTimeout", set_timeout, 1, attr);
  77. define_native_function("clearInterval", clear_interval, 1, attr);
  78. define_native_function("clearTimeout", clear_timeout, 1, attr);
  79. define_native_function("requestAnimationFrame", request_animation_frame, 1, attr);
  80. define_native_function("cancelAnimationFrame", cancel_animation_frame, 1, attr);
  81. define_native_function("atob", atob, 1, attr);
  82. define_native_function("btoa", btoa, 1, attr);
  83. define_native_function("queueMicrotask", queue_microtask, 1, attr);
  84. define_native_function("getComputedStyle", get_computed_style, 1, attr);
  85. define_native_function("matchMedia", match_media, 1, attr);
  86. define_native_function("getSelection", get_selection, 0, attr);
  87. // FIXME: These properties should be [Replaceable] according to the spec, but [Writable+Configurable] is the closest we have.
  88. define_native_accessor("scrollX", scroll_x_getter, {}, attr);
  89. define_native_accessor("pageXOffset", scroll_x_getter, {}, attr);
  90. define_native_accessor("scrollY", scroll_y_getter, {}, attr);
  91. define_native_accessor("pageYOffset", scroll_y_getter, {}, attr);
  92. define_native_function("scroll", scroll, 2, attr);
  93. define_native_function("scrollTo", scroll, 2, attr);
  94. define_native_function("scrollBy", scroll_by, 2, attr);
  95. define_native_accessor("screenX", screen_x_getter, {}, attr);
  96. define_native_accessor("screenY", screen_y_getter, {}, attr);
  97. define_native_accessor("screenLeft", screen_left_getter, {}, attr);
  98. define_native_accessor("screenTop", screen_top_getter, {}, attr);
  99. define_direct_property("CSS", heap().allocate<CSSNamespace>(*this, *this), 0);
  100. // Legacy
  101. define_native_accessor("event", event_getter, event_setter, JS::Attribute::Enumerable);
  102. m_location_object = heap().allocate<LocationObject>(*this, *this);
  103. define_direct_property("navigator", heap().allocate<NavigatorObject>(*this, *this), JS::Attribute::Enumerable | JS::Attribute::Configurable);
  104. // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable.
  105. define_direct_property("location", m_location_object, JS::Attribute::Enumerable);
  106. // WebAssembly "namespace"
  107. define_direct_property("WebAssembly", heap().allocate<WebAssemblyObject>(*this, *this), JS::Attribute::Enumerable | JS::Attribute::Configurable);
  108. // HTML::GlobalEventHandlers
  109. #define __ENUMERATE(attribute, event_name) \
  110. define_native_accessor(#attribute, attribute##_getter, attribute##_setter, attr);
  111. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE);
  112. #undef __ENUMERATE
  113. ADD_WINDOW_OBJECT_INTERFACES;
  114. }
  115. WindowObject::~WindowObject()
  116. {
  117. }
  118. void WindowObject::visit_edges(Visitor& visitor)
  119. {
  120. GlobalObject::visit_edges(visitor);
  121. visitor.visit(m_location_object);
  122. for (auto& it : m_prototypes)
  123. visitor.visit(it.value);
  124. for (auto& it : m_constructors)
  125. visitor.visit(it.value);
  126. }
  127. Origin WindowObject::origin() const
  128. {
  129. return impl().associated_document().origin();
  130. }
  131. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  132. JS::ThrowCompletionOr<bool> WindowObject::internal_set_prototype_of(JS::Object* prototype)
  133. {
  134. // 1. Return ? SetImmutablePrototype(O, V).
  135. return set_immutable_prototype(prototype);
  136. }
  137. static JS::ThrowCompletionOr<DOM::Window*> impl_from(JS::VM& vm, JS::GlobalObject& global_object)
  138. {
  139. // Since this is a non built-in function we must treat it as non-strict mode
  140. // this means that a nullish this_value should be converted to the
  141. // global_object. Generally this does not matter as we try to convert the
  142. // this_value to a specific object type in the bindings. But since window is
  143. // the global object we make an exception here.
  144. // This allows calls like `setTimeout(f, 10)` to work.
  145. auto this_value = vm.this_value(global_object);
  146. if (this_value.is_nullish())
  147. this_value = &global_object;
  148. auto* this_object = MUST(this_value.to_object(global_object));
  149. if (StringView("WindowObject") != this_object->class_name())
  150. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "WindowObject");
  151. return &static_cast<WindowObject*>(this_object)->impl();
  152. }
  153. JS_DEFINE_NATIVE_FUNCTION(WindowObject::alert)
  154. {
  155. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  156. // Note: This method is defined using two overloads, instead of using an optional argument,
  157. // for historical reasons. The practical impact of this is that alert(undefined) is
  158. // treated as alert("undefined"), but alert() is treated as alert("").
  159. auto* impl = TRY(impl_from(vm, global_object));
  160. String message = "";
  161. if (vm.argument_count())
  162. message = TRY(vm.argument(0).to_string(global_object));
  163. impl->alert(message);
  164. return JS::js_undefined();
  165. }
  166. JS_DEFINE_NATIVE_FUNCTION(WindowObject::confirm)
  167. {
  168. auto* impl = TRY(impl_from(vm, global_object));
  169. String message = "";
  170. if (!vm.argument(0).is_undefined())
  171. message = TRY(vm.argument(0).to_string(global_object));
  172. return JS::Value(impl->confirm(message));
  173. }
  174. JS_DEFINE_NATIVE_FUNCTION(WindowObject::prompt)
  175. {
  176. auto* impl = TRY(impl_from(vm, global_object));
  177. String message = "";
  178. String default_ = "";
  179. if (!vm.argument(0).is_undefined())
  180. message = TRY(vm.argument(0).to_string(global_object));
  181. if (!vm.argument(1).is_undefined())
  182. default_ = TRY(vm.argument(1).to_string(global_object));
  183. auto response = impl->prompt(message, default_);
  184. if (response.is_null())
  185. return JS::js_null();
  186. return JS::js_string(vm, response);
  187. }
  188. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  189. JS_DEFINE_NATIVE_FUNCTION(WindowObject::set_interval)
  190. {
  191. // FIXME: Ideally this would share more code with setTimeout() using the "timer initialization steps"
  192. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  193. auto* impl = TRY(impl_from(vm, global_object));
  194. if (!vm.argument_count())
  195. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
  196. JS::FunctionObject* callback;
  197. if (vm.argument(0).is_function()) {
  198. callback = &vm.argument(0).as_function();
  199. } else {
  200. auto script_source = TRY(vm.argument(0).to_string(global_object));
  201. // FIXME: This needs more work once we have a environment settings object.
  202. // The spec wants us to use a task for the "run function or script string" part,
  203. // using a NativeFunction for the latter is a workaround so that we can reuse the
  204. // DOM::Timer API unaltered (always expects a JS::FunctionObject).
  205. callback = JS::NativeFunction::create(global_object, "", [impl, script_source = move(script_source)](auto&, auto&) mutable {
  206. auto& settings_object = verify_cast<HTML::EnvironmentSettingsObject>(*impl->associated_document().realm().host_defined());
  207. auto script = HTML::ClassicScript::create(impl->associated_document().url().to_string(), script_source, settings_object, AK::URL());
  208. return script->run();
  209. });
  210. }
  211. i32 interval = 0;
  212. if (vm.argument_count() >= 2) {
  213. interval = TRY(vm.argument(1).to_i32(global_object));
  214. if (interval < 0)
  215. interval = 0;
  216. }
  217. // FIXME: Pass ...arguments to the callback function when it's invoked
  218. auto timer_id = impl->set_interval(*callback, interval);
  219. return JS::Value(timer_id);
  220. }
  221. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  222. JS_DEFINE_NATIVE_FUNCTION(WindowObject::set_timeout)
  223. {
  224. // FIXME: Ideally this would share more code with setInterval() using the "timer initialization steps"
  225. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  226. auto* impl = TRY(impl_from(vm, global_object));
  227. if (!vm.argument_count())
  228. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
  229. JS::FunctionObject* callback;
  230. if (vm.argument(0).is_function()) {
  231. callback = &vm.argument(0).as_function();
  232. } else {
  233. auto script_source = TRY(vm.argument(0).to_string(global_object));
  234. // FIXME: This needs more work once we have a environment settings object.
  235. // The spec wants us to use a task for the "run function or script string" part,
  236. // using a NativeFunction for the latter is a workaround so that we can reuse the
  237. // DOM::Timer API unaltered (always expects a JS::FunctionObject).
  238. callback = JS::NativeFunction::create(global_object, "", [impl, script_source = move(script_source)](auto&, auto&) mutable {
  239. auto& settings_object = verify_cast<HTML::EnvironmentSettingsObject>(*impl->associated_document().realm().host_defined());
  240. auto script = HTML::ClassicScript::create(impl->associated_document().url().to_string(), script_source, settings_object, AK::URL());
  241. return script->run();
  242. });
  243. }
  244. i32 interval = 0;
  245. if (vm.argument_count() >= 2) {
  246. interval = TRY(vm.argument(1).to_i32(global_object));
  247. if (interval < 0)
  248. interval = 0;
  249. }
  250. // FIXME: Pass ...arguments to the callback function when it's invoked
  251. auto timer_id = impl->set_timeout(*callback, interval);
  252. return JS::Value(timer_id);
  253. }
  254. JS_DEFINE_NATIVE_FUNCTION(WindowObject::clear_timeout)
  255. {
  256. auto* impl = TRY(impl_from(vm, global_object));
  257. if (!vm.argument_count())
  258. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "clearTimeout");
  259. i32 timer_id = TRY(vm.argument(0).to_i32(global_object));
  260. impl->clear_timeout(timer_id);
  261. return JS::js_undefined();
  262. }
  263. JS_DEFINE_NATIVE_FUNCTION(WindowObject::clear_interval)
  264. {
  265. auto* impl = TRY(impl_from(vm, global_object));
  266. if (!vm.argument_count())
  267. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "clearInterval");
  268. i32 timer_id = TRY(vm.argument(0).to_i32(global_object));
  269. impl->clear_interval(timer_id);
  270. return JS::js_undefined();
  271. }
  272. JS_DEFINE_NATIVE_FUNCTION(WindowObject::request_animation_frame)
  273. {
  274. auto* impl = TRY(impl_from(vm, global_object));
  275. if (!vm.argument_count())
  276. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "requestAnimationFrame");
  277. auto* callback_object = TRY(vm.argument(0).to_object(global_object));
  278. if (!callback_object->is_function())
  279. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAFunctionNoParam);
  280. return JS::Value(impl->request_animation_frame(*static_cast<JS::FunctionObject*>(callback_object)));
  281. }
  282. JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_animation_frame)
  283. {
  284. auto* impl = TRY(impl_from(vm, global_object));
  285. if (!vm.argument_count())
  286. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "cancelAnimationFrame");
  287. auto id = TRY(vm.argument(0).to_i32(global_object));
  288. impl->cancel_animation_frame(id);
  289. return JS::js_undefined();
  290. }
  291. JS_DEFINE_NATIVE_FUNCTION(WindowObject::queue_microtask)
  292. {
  293. auto* impl = TRY(impl_from(vm, global_object));
  294. if (!vm.argument_count())
  295. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "queueMicrotask");
  296. auto* callback_object = TRY(vm.argument(0).to_object(global_object));
  297. if (!callback_object->is_function())
  298. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAFunctionNoParam);
  299. impl->queue_microtask(static_cast<JS::FunctionObject&>(*callback_object));
  300. return JS::js_undefined();
  301. }
  302. JS_DEFINE_NATIVE_FUNCTION(WindowObject::atob)
  303. {
  304. if (!vm.argument_count())
  305. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "atob");
  306. auto string = TRY(vm.argument(0).to_string(global_object));
  307. auto decoded = decode_base64(StringView(string));
  308. if (decoded.is_error())
  309. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::InvalidFormat, "Base64");
  310. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  311. auto decoder = TextCodec::decoder_for("windows-1252");
  312. VERIFY(decoder);
  313. return JS::js_string(vm, decoder->to_utf8(decoded.value()));
  314. }
  315. JS_DEFINE_NATIVE_FUNCTION(WindowObject::btoa)
  316. {
  317. if (!vm.argument_count())
  318. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "btoa");
  319. auto string = TRY(vm.argument(0).to_string(global_object));
  320. Vector<u8> byte_string;
  321. byte_string.ensure_capacity(string.length());
  322. for (u32 code_point : Utf8View(string)) {
  323. if (code_point > 0xff)
  324. return vm.throw_completion<JS::InvalidCharacterError>(global_object, JS::ErrorType::NotAByteString, "btoa");
  325. byte_string.append(code_point);
  326. }
  327. auto encoded = encode_base64(byte_string.span());
  328. return JS::js_string(vm, move(encoded));
  329. }
  330. // https://html.spec.whatwg.org/multipage/browsers.html#dom-top
  331. JS_DEFINE_NATIVE_FUNCTION(WindowObject::top_getter)
  332. {
  333. auto* impl = TRY(impl_from(vm, global_object));
  334. auto* this_browsing_context = impl->associated_document().browsing_context();
  335. if (!this_browsing_context)
  336. return JS::js_null();
  337. VERIFY(this_browsing_context->top_level_browsing_context().active_document());
  338. auto& top_window = this_browsing_context->top_level_browsing_context().active_document()->window();
  339. return top_window.wrapper();
  340. }
  341. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  342. JS_DEFINE_NATIVE_FUNCTION(WindowObject::parent_getter)
  343. {
  344. auto* impl = TRY(impl_from(vm, global_object));
  345. auto* this_browsing_context = impl->associated_document().browsing_context();
  346. if (!this_browsing_context)
  347. return JS::js_null();
  348. if (this_browsing_context->parent()) {
  349. VERIFY(this_browsing_context->parent()->active_document());
  350. auto& parent_window = this_browsing_context->parent()->active_document()->window();
  351. return parent_window.wrapper();
  352. }
  353. VERIFY(this_browsing_context == &this_browsing_context->top_level_browsing_context());
  354. return impl->wrapper();
  355. }
  356. JS_DEFINE_NATIVE_FUNCTION(WindowObject::document_getter)
  357. {
  358. auto* impl = TRY(impl_from(vm, global_object));
  359. return wrap(global_object, impl->associated_document());
  360. }
  361. JS_DEFINE_NATIVE_FUNCTION(WindowObject::performance_getter)
  362. {
  363. auto* impl = TRY(impl_from(vm, global_object));
  364. return wrap(global_object, impl->performance());
  365. }
  366. JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_getter)
  367. {
  368. auto* impl = TRY(impl_from(vm, global_object));
  369. return wrap(global_object, impl->screen());
  370. }
  371. JS_DEFINE_NATIVE_FUNCTION(WindowObject::event_getter)
  372. {
  373. auto* impl = TRY(impl_from(vm, global_object));
  374. if (!impl->current_event())
  375. return JS::js_undefined();
  376. return wrap(global_object, const_cast<DOM::Event&>(*impl->current_event()));
  377. }
  378. JS_DEFINE_NATIVE_FUNCTION(WindowObject::event_setter)
  379. {
  380. REPLACEABLE_PROPERTY_SETTER(WindowObject, event);
  381. }
  382. JS_DEFINE_NATIVE_FUNCTION(WindowObject::crypto_getter)
  383. {
  384. auto* impl = TRY(impl_from(vm, global_object));
  385. return wrap(global_object, impl->crypto());
  386. }
  387. JS_DEFINE_NATIVE_FUNCTION(WindowObject::inner_width_getter)
  388. {
  389. auto* impl = TRY(impl_from(vm, global_object));
  390. return JS::Value(impl->inner_width());
  391. }
  392. JS_DEFINE_NATIVE_FUNCTION(WindowObject::inner_height_getter)
  393. {
  394. auto* impl = TRY(impl_from(vm, global_object));
  395. return JS::Value(impl->inner_height());
  396. }
  397. JS_DEFINE_NATIVE_FUNCTION(WindowObject::device_pixel_ratio_getter)
  398. {
  399. auto* impl = TRY(impl_from(vm, global_object));
  400. return JS::Value(impl->device_pixel_ratio());
  401. }
  402. JS_DEFINE_NATIVE_FUNCTION(WindowObject::get_computed_style)
  403. {
  404. auto* impl = TRY(impl_from(vm, global_object));
  405. auto* object = TRY(vm.argument(0).to_object(global_object));
  406. if (!is<ElementWrapper>(object))
  407. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "DOM element");
  408. return wrap(global_object, impl->get_computed_style(static_cast<ElementWrapper*>(object)->impl()));
  409. }
  410. JS_DEFINE_NATIVE_FUNCTION(WindowObject::get_selection)
  411. {
  412. auto* impl = TRY(impl_from(vm, global_object));
  413. auto* selection = impl->get_selection();
  414. if (!selection)
  415. return JS::js_null();
  416. return wrap(global_object, *selection);
  417. }
  418. JS_DEFINE_NATIVE_FUNCTION(WindowObject::match_media)
  419. {
  420. auto* impl = TRY(impl_from(vm, global_object));
  421. auto media = TRY(vm.argument(0).to_string(global_object));
  422. return wrap(global_object, impl->match_media(move(media)));
  423. }
  424. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  425. JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_x_getter)
  426. {
  427. auto* impl = TRY(impl_from(vm, global_object));
  428. return JS::Value(impl->scroll_x());
  429. }
  430. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  431. JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_y_getter)
  432. {
  433. auto* impl = TRY(impl_from(vm, global_object));
  434. return JS::Value(impl->scroll_y());
  435. }
  436. enum class ScrollBehavior {
  437. Auto,
  438. Smooth
  439. };
  440. // https://www.w3.org/TR/cssom-view/#perform-a-scroll
  441. static void perform_a_scroll(Page& page, double x, double y, ScrollBehavior)
  442. {
  443. // FIXME: Stop any existing smooth-scrolls
  444. // FIXME: Implement smooth-scroll
  445. page.client().page_did_request_scroll_to({ x, y });
  446. }
  447. // https://www.w3.org/TR/cssom-view/#dom-window-scroll
  448. JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll)
  449. {
  450. auto* impl = TRY(impl_from(vm, global_object));
  451. if (!impl->page())
  452. return JS::js_undefined();
  453. auto& page = *impl->page();
  454. auto viewport_rect = page.top_level_browsing_context().viewport_rect();
  455. auto x_value = JS::Value(viewport_rect.x());
  456. auto y_value = JS::Value(viewport_rect.y());
  457. String behavior_string = "auto";
  458. if (vm.argument_count() == 1) {
  459. auto* options = TRY(vm.argument(0).to_object(global_object));
  460. auto left = TRY(options->get("left"));
  461. if (!left.is_undefined())
  462. x_value = left;
  463. auto top = TRY(options->get("top"));
  464. if (!top.is_undefined())
  465. y_value = top;
  466. auto behavior_string_value = TRY(options->get("behavior"));
  467. if (!behavior_string_value.is_undefined())
  468. behavior_string = TRY(behavior_string_value.to_string(global_object));
  469. if (behavior_string != "smooth" && behavior_string != "auto")
  470. return vm.throw_completion<JS::TypeError>(global_object, "Behavior is not one of 'smooth' or 'auto'");
  471. } else if (vm.argument_count() >= 2) {
  472. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  473. x_value = vm.argument(0);
  474. y_value = vm.argument(1);
  475. }
  476. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  477. double x = TRY(x_value.to_double(global_object));
  478. x = JS::Value(x).is_finite_number() ? x : 0.0;
  479. double y = TRY(y_value.to_double(global_object));
  480. y = JS::Value(y).is_finite_number() ? y : 0.0;
  481. // FIXME: Are we calculating the viewport in the way this function expects?
  482. // FIXME: Handle overflow-directions other than top-left to bottom-right
  483. perform_a_scroll(page, x, y, behavior);
  484. return JS::js_undefined();
  485. }
  486. // https://www.w3.org/TR/cssom-view/#dom-window-scrollby
  487. JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_by)
  488. {
  489. auto* impl = TRY(impl_from(vm, global_object));
  490. if (!impl->page())
  491. return JS::js_undefined();
  492. auto& page = *impl->page();
  493. JS::Object* options = nullptr;
  494. if (vm.argument_count() == 0) {
  495. options = JS::Object::create(global_object, nullptr);
  496. } else if (vm.argument_count() == 1) {
  497. options = TRY(vm.argument(0).to_object(global_object));
  498. } else if (vm.argument_count() >= 2) {
  499. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  500. options = JS::Object::create(global_object, nullptr);
  501. MUST(options->set("left", vm.argument(0), ShouldThrowExceptions::No));
  502. MUST(options->set("top", vm.argument(1), ShouldThrowExceptions::No));
  503. MUST(options->set("behavior", JS::js_string(vm, "auto"), ShouldThrowExceptions::No));
  504. }
  505. auto left_value = TRY(options->get("left"));
  506. auto left = TRY(left_value.to_double(global_object));
  507. auto top_value = TRY(options->get("top"));
  508. auto top = TRY(top_value.to_double(global_object));
  509. left = JS::Value(left).is_finite_number() ? left : 0.0;
  510. top = JS::Value(top).is_finite_number() ? top : 0.0;
  511. auto current_scroll_position = page.top_level_browsing_context().viewport_scroll_offset();
  512. left = left + current_scroll_position.x();
  513. top = top + current_scroll_position.y();
  514. auto behavior_string_value = TRY(options->get("behavior"));
  515. auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY(behavior_string_value.to_string(global_object));
  516. if (behavior_string != "smooth" && behavior_string != "auto")
  517. return vm.throw_completion<JS::TypeError>(global_object, "Behavior is not one of 'smooth' or 'auto'");
  518. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  519. // FIXME: Spec wants us to call scroll(options) here.
  520. // The only difference is that would invoke the viewport calculations that scroll()
  521. // is not actually doing yet, so this is the same for now.
  522. perform_a_scroll(page, left, top, behavior);
  523. return JS::js_undefined();
  524. }
  525. JS_DEFINE_NATIVE_FUNCTION(WindowObject::history_getter)
  526. {
  527. auto* impl = TRY(impl_from(vm, global_object));
  528. return wrap(global_object, impl->associated_document().history());
  529. }
  530. JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_left_getter)
  531. {
  532. auto* impl = TRY(impl_from(vm, global_object));
  533. return JS::Value(impl->screen_x());
  534. }
  535. JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_top_getter)
  536. {
  537. auto* impl = TRY(impl_from(vm, global_object));
  538. return JS::Value(impl->screen_y());
  539. }
  540. JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_x_getter)
  541. {
  542. auto* impl = TRY(impl_from(vm, global_object));
  543. return JS::Value(impl->screen_x());
  544. }
  545. JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_y_getter)
  546. {
  547. auto* impl = TRY(impl_from(vm, global_object));
  548. return JS::Value(impl->screen_y());
  549. }
  550. #define __ENUMERATE(attribute, event_name) \
  551. JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_getter) \
  552. { \
  553. auto* impl = TRY(impl_from(vm, global_object)); \
  554. auto retval = impl->attribute(); \
  555. if (retval.callback.is_null()) \
  556. return JS::js_null(); \
  557. return retval.callback.cell(); \
  558. } \
  559. JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_setter) \
  560. { \
  561. auto* impl = TRY(impl_from(vm, global_object)); \
  562. auto value = vm.argument(0); \
  563. HTML::EventHandler cpp_value; \
  564. if (value.is_function()) { \
  565. cpp_value.callback = JS::make_handle(&value.as_function()); \
  566. } else if (value.is_string()) { \
  567. cpp_value.string = value.as_string().string(); \
  568. } else { \
  569. return JS::js_undefined(); \
  570. } \
  571. TRY(throw_dom_exception_if_needed(global_object, [&] { \
  572. return impl->set_##attribute(cpp_value); \
  573. })); \
  574. return JS::js_undefined(); \
  575. }
  576. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  577. #undef __ENUMERATE
  578. }