Worker.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. public:
  28. static WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> create(String const& script_url, WorkerOptions const options, DOM::Document& document);
  29. static WebIDL::ExceptionOr<JS::NonnullGCPtr<Worker>> construct_impl(JS::Realm& realm, String const& script_url, WorkerOptions const options)
  30. {
  31. auto& window = verify_cast<HTML::Window>(realm.global_object());
  32. return Worker::create(script_url, options, window.associated_document());
  33. }
  34. WebIDL::ExceptionOr<void> terminate();
  35. void post_message(JS::Value message, JS::Value transfer);
  36. virtual ~Worker() = default;
  37. JS::GCPtr<MessagePort> outside_message_port() { return m_outside_port; }
  38. #undef __ENUMERATE
  39. #define __ENUMERATE(attribute_name, event_name) \
  40. void set_##attribute_name(WebIDL::CallbackType*); \
  41. WebIDL::CallbackType* attribute_name();
  42. ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
  43. #undef __ENUMERATE
  44. protected:
  45. Worker(String const&, const WorkerOptions, DOM::Document&);
  46. private:
  47. virtual void initialize(JS::Realm&) override;
  48. virtual void visit_edges(Cell::Visitor&) override;
  49. String m_script_url;
  50. WorkerOptions m_options;
  51. JS::GCPtr<DOM::Document> m_document;
  52. JS::GCPtr<MessagePort> m_outside_port;
  53. JS::GCPtr<WorkerAgent> m_agent;
  54. void run_a_worker(AK::URL& url, EnvironmentSettingsObject& outside_settings, MessagePort& outside_port, WorkerOptions const& options);
  55. };
  56. }