AudioConstructor.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/AudioConstructor.h>
  7. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  8. #include <LibWeb/Bindings/HTMLAudioElementPrototype.h>
  9. #include <LibWeb/DOM/ElementFactory.h>
  10. #include <LibWeb/HTML/Scripting/Environments.h>
  11. #include <LibWeb/HTML/Window.h>
  12. #include <LibWeb/Namespace.h>
  13. namespace Web::Bindings {
  14. AudioConstructor::AudioConstructor(JS::Realm& realm)
  15. : NativeFunction(realm.intrinsics().function_prototype())
  16. {
  17. }
  18. JS::ThrowCompletionOr<void> AudioConstructor::initialize(JS::Realm& realm)
  19. {
  20. auto& vm = this->vm();
  21. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  22. define_direct_property(vm.names.prototype, &ensure_web_prototype<Bindings::HTMLAudioElementPrototype>(realm, "HTMLAudioElement"), 0);
  23. define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
  24. return {};
  25. }
  26. JS::ThrowCompletionOr<JS::Value> AudioConstructor::call()
  27. {
  28. return vm().throw_completion<JS::TypeError>(JS::ErrorType::ConstructorWithoutNew, "Audio");
  29. }
  30. // https://html.spec.whatwg.org/multipage/media.html#dom-audio
  31. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> AudioConstructor::construct(FunctionObject&)
  32. {
  33. auto& vm = this->vm();
  34. // 1. Let document be the current global object's associated Document.
  35. auto& window = verify_cast<HTML::Window>(HTML::current_global_object());
  36. auto& document = window.associated_document();
  37. // 2. Let audio be the result of creating an element given document, audio, and the HTML namespace.
  38. auto audio = TRY(Bindings::throw_dom_exception_if_needed(vm, [&]() { return DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML); }));
  39. // 3. Set an attribute value for audio using "preload" and "auto".
  40. MUST(audio->set_attribute(HTML::AttributeNames::preload, "auto"sv));
  41. auto src_value = vm.argument(0);
  42. // 4. If src is given, then set an attribute value for audio using "src" and src.
  43. // (This will cause the user agent to invoke the object's resource selection algorithm before returning.)
  44. if (!src_value.is_undefined()) {
  45. auto src = TRY(src_value.to_deprecated_string(vm));
  46. MUST(audio->set_attribute(HTML::AttributeNames::src, move(src)));
  47. }
  48. // 5. Return audio.
  49. return audio;
  50. }
  51. }