Skip to main content

script/dom/
broadcastchannel.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 std::cell::Cell;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::rust::{HandleObject, HandleValue};
10use script_bindings::reflector::reflect_dom_object_with_proto_and_cx;
11use servo_constellation_traits::BroadcastChannelMsg;
12use uuid::Uuid;
13
14use crate::dom::bindings::codegen::Bindings::BroadcastChannelBinding::BroadcastChannelMethods;
15use crate::dom::bindings::error::{Error, ErrorResult};
16use crate::dom::bindings::reflector::DomGlobal;
17use crate::dom::bindings::root::DomRoot;
18use crate::dom::bindings::str::DOMString;
19use crate::dom::bindings::structuredclone;
20use crate::dom::eventtarget::EventTarget;
21use crate::dom::globalscope::GlobalScope;
22
23#[dom_struct]
24pub(crate) struct BroadcastChannel {
25    eventtarget: EventTarget,
26    name: DOMString,
27    closed: Cell<bool>,
28    #[no_trace]
29    id: Uuid,
30}
31
32impl BroadcastChannel {
33    fn new(
34        cx: &mut JSContext,
35        global: &GlobalScope,
36        proto: Option<HandleObject>,
37        name: DOMString,
38    ) -> DomRoot<BroadcastChannel> {
39        let channel = reflect_dom_object_with_proto_and_cx(
40            Box::new(BroadcastChannel::new_inherited(name)),
41            global,
42            proto,
43            cx,
44        );
45        global.track_broadcast_channel(&channel);
46        channel
47    }
48
49    pub(crate) fn new_inherited(name: DOMString) -> BroadcastChannel {
50        BroadcastChannel {
51            eventtarget: EventTarget::new_inherited(),
52            name,
53            closed: Default::default(),
54            id: Uuid::new_v4(),
55        }
56    }
57
58    /// The unique Id of this channel.
59    /// Used for filtering out the sender from the local broadcast.
60    pub(crate) fn id(&self) -> &Uuid {
61        &self.id
62    }
63
64    /// Is this channel closed?
65    pub(crate) fn closed(&self) -> bool {
66        self.closed.get()
67    }
68}
69
70impl BroadcastChannelMethods<crate::DomTypeHolder> for BroadcastChannel {
71    /// <https://html.spec.whatwg.org/multipage/#broadcastchannel>
72    fn Constructor(
73        cx: &mut JSContext,
74        global: &GlobalScope,
75        proto: Option<HandleObject>,
76        name: DOMString,
77    ) -> DomRoot<BroadcastChannel> {
78        BroadcastChannel::new(cx, global, proto, name)
79    }
80
81    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
82    fn PostMessage(&self, cx: &mut JSContext, message: HandleValue) -> ErrorResult {
83        // Step 3, if closed.
84        if self.closed.get() {
85            return Err(Error::InvalidState(Some(
86                "Cannot post message on a closed BroadcastChannel".to_string(),
87            )));
88        }
89
90        // Step 6, StructuredSerialize(message).
91        let data = structuredclone::write(cx, message, None)?;
92
93        let global = self.global();
94
95        let msg = BroadcastChannelMsg {
96            origin: global.origin().immutable().clone(),
97            channel_name: String::from(self.Name()),
98            data,
99        };
100
101        global.schedule_broadcast(msg, &self.id);
102        Ok(())
103    }
104
105    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-name>
106    fn Name(&self) -> DOMString {
107        self.name.clone()
108    }
109
110    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-close>
111    fn Close(&self) {
112        self.closed.set(true);
113    }
114
115    // <https://html.spec.whatwg.org/multipage/#handler-broadcastchannel-onmessageerror>
116    event_handler!(messageerror, GetOnmessageerror, SetOnmessageerror);
117
118    // <https://html.spec.whatwg.org/multipage/#handler-broadcastchannel-onmessage>
119    event_handler!(message, GetOnmessage, SetOnmessage);
120}