Worker.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/RefCounted.h>
  8. #include <AK/URLParser.h>
  9. #include <LibWeb/Bindings/MainThreadVM.h>
  10. #include <LibWeb/Forward.h>
  11. #include <LibWeb/HTML/MessageEvent.h>
  12. #include <LibWeb/HTML/MessagePort.h>
  13. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  14. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  15. #include <LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h>
  16. #include <LibWeb/HTML/Window.h>
  17. #include <LibWeb/HTML/WorkerAgent.h>
  18. #include <LibWeb/HTML/WorkerDebugConsoleClient.h>
  19. #include <LibWeb/Loader/ResourceLoader.h>
  20. #define ENUMERATE_WORKER_EVENT_HANDLERS(E) \
  21. E(onmessage, HTML::EventNames::message) \
  22. E(onmessageerror, HTML::EventNames::messageerror)
  23. namespace Web::HTML {
  24. // https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
  25. class Worker : public DOM::EventTarget {
  26. WEB_PLATFORM_OBJECT(Worker, DOM::EventTarget);
  27. JS_DECLARE_ALLOCATOR(Worker);
  28. public:
  29. static WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> create(String const& script_url, WorkerOptions const& options, DOM::Document& document);
  30. static WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> construct_impl(JS::Realm& realm, String const& script_url, WorkerOptions const& options)
  31. {
  32. auto& window = verify_cast<HTML::Window>(realm.global_object());
  33. return Worker::create(script_url, options, window.associated_document());
  34. }
  35. WebIDL::ExceptionOr<void> terminate();
  36. WebIDL::ExceptionOr<void> post_message(JS::Value message, StructuredSerializeOptions const&);
  37. virtual ~Worker() = default;
  38. JS::GCPtr<MessagePort> outside_message_port() { return m_outside_port; }
  39. #undef __ENUMERATE
  40. #define __ENUMERATE(attribute_name, event_name) \
  41. void set_##attribute_name(WebIDL::CallbackType*); \
  42. WebIDL::CallbackType* attribute_name();
  43. ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
  44. #undef __ENUMERATE
  45. protected:
  46. Worker(String const&, WorkerOptions const&, DOM::Document&);
  47. private:
  48. virtual void initialize(JS::Realm&) override;
  49. virtual void visit_edges(Cell::Visitor&) override;
  50. String m_script_url;
  51. WorkerOptions m_options;
  52. JS::GCPtr<DOM::Document> m_document;
  53. JS::GCPtr<MessagePort> m_outside_port;
  54. JS::GCPtr<WorkerAgent> m_agent;
  55. void run_a_worker(URL& url, EnvironmentSettingsObject& outside_settings, JS::GCPtr<MessagePort> outside_port, WorkerOptions const& options);
  56. };
  57. }