Skip to main content

script/dom/globalscope/
messagechannel.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::JSContext;
7use js::rust::HandleObject;
8use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto_and_cx};
9
10use crate::dom::bindings::codegen::Bindings::MessageChannelBinding::MessageChannelMethods;
11use crate::dom::bindings::root::{Dom, DomRoot};
12use crate::dom::globalscope::GlobalScope;
13use crate::dom::messageport::MessagePort;
14
15#[dom_struct]
16pub(crate) struct MessageChannel {
17    reflector_: Reflector,
18    port1: Dom<MessagePort>,
19    port2: Dom<MessagePort>,
20}
21
22impl MessageChannel {
23    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
24    fn new(
25        cx: &mut JSContext,
26        incumbent: &GlobalScope,
27        proto: Option<HandleObject>,
28    ) -> DomRoot<MessageChannel> {
29        // Step 1
30        let port1 = MessagePort::new(cx, incumbent);
31
32        // Step 2
33        let port2 = MessagePort::new(cx, incumbent);
34
35        incumbent.track_message_port(&port1, None);
36        incumbent.track_message_port(&port2, None);
37
38        // Step 3
39        incumbent.entangle_ports(*port1.message_port_id(), *port2.message_port_id());
40
41        // Steps 4-6
42        reflect_dom_object_with_proto_and_cx(
43            Box::new(MessageChannel::new_inherited(&port1, &port2)),
44            incumbent,
45            proto,
46            cx,
47        )
48    }
49
50    pub(crate) fn new_inherited(port1: &MessagePort, port2: &MessagePort) -> MessageChannel {
51        MessageChannel {
52            reflector_: Reflector::new(),
53            port1: Dom::from_ref(port1),
54            port2: Dom::from_ref(port2),
55        }
56    }
57}
58
59impl MessageChannelMethods<crate::DomTypeHolder> for MessageChannel {
60    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
61    fn Constructor(
62        cx: &mut JSContext,
63        global: &GlobalScope,
64        proto: Option<HandleObject>,
65    ) -> DomRoot<MessageChannel> {
66        MessageChannel::new(cx, global, proto)
67    }
68
69    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel-port1>
70    fn Port1(&self) -> DomRoot<MessagePort> {
71        DomRoot::from_ref(&*self.port1)
72    }
73
74    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel-port2>
75    fn Port2(&self) -> DomRoot<MessagePort> {
76        DomRoot::from_ref(&*self.port2)
77    }
78}