AudioConstructor.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/HTMLAudioElementPrototype.h>
  8. #include <LibWeb/Bindings/HTMLAudioElementWrapper.h>
  9. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  10. #include <LibWeb/DOM/ElementFactory.h>
  11. #include <LibWeb/HTML/Window.h>
  12. #include <LibWeb/Namespace.h>
  13. namespace Web::Bindings {
  14. AudioConstructor::AudioConstructor(JS::GlobalObject& global_object)
  15. : NativeFunction(*global_object.function_prototype())
  16. {
  17. }
  18. void AudioConstructor::initialize(JS::GlobalObject& global_object)
  19. {
  20. auto& vm = this->vm();
  21. auto& window = static_cast<WindowObject&>(global_object);
  22. NativeFunction::initialize(global_object);
  23. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<HTMLAudioElementPrototype>("HTMLAudioElement"), 0);
  24. define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
  25. }
  26. JS::ThrowCompletionOr<JS::Value> AudioConstructor::call()
  27. {
  28. return vm().throw_completion<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "Audio");
  29. }
  30. // https://html.spec.whatwg.org/multipage/media.html#dom-audio
  31. JS::ThrowCompletionOr<JS::Object*> AudioConstructor::construct(FunctionObject&)
  32. {
  33. // 1. Let document be the current global object's associated Document.
  34. auto& window = static_cast<WindowObject&>(HTML::current_global_object());
  35. auto& document = window.impl().associated_document();
  36. // 2. Let audio be the result of creating an element given document, audio, and the HTML namespace.
  37. auto audio = DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML);
  38. // 3. Set an attribute value for audio using "preload" and "auto".
  39. audio->set_attribute(HTML::AttributeNames::preload, "auto"sv);
  40. auto src_value = vm().argument(0);
  41. // 4. If src is given, then set an attribute value for audio using "src" and src.
  42. // (This will cause the user agent to invoke the object's resource selection algorithm before returning.)
  43. if (!src_value.is_undefined()) {
  44. auto src = TRY(src_value.to_string(global_object()));
  45. audio->set_attribute(HTML::AttributeNames::src, move(src));
  46. }
  47. // 5. Return audio.
  48. return wrap(global_object(), audio);
  49. }
  50. }