Skip to main content

script/dom/event/
beforeunloadevent.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 https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::JSContext;
7use script_bindings::cell::DomRefCell;
8use script_bindings::domstring::TracedDOMString;
9use script_bindings::reflector::reflect_dom_object;
10use stylo_atoms::Atom;
11
12use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
13use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
14use crate::dom::bindings::inheritance::Castable;
15use crate::dom::bindings::root::DomRoot;
16use crate::dom::bindings::str::DOMString;
17use crate::dom::event::{Event, EventBubbles, EventCancelable};
18use crate::dom::window::Window;
19
20/// <https://html.spec.whatwg.org/multipage/#beforeunloadevent>
21#[dom_struct]
22pub(crate) struct BeforeUnloadEvent {
23    event: Event,
24    return_value: DomRefCell<TracedDOMString>,
25}
26
27impl BeforeUnloadEvent {
28    fn new_inherited() -> BeforeUnloadEvent {
29        BeforeUnloadEvent {
30            event: Event::new_inherited(),
31            return_value: DomRefCell::new(DOMString::new().traced()),
32        }
33    }
34
35    pub(crate) fn new_uninitialized(
36        cx: &mut JSContext,
37        window: &Window,
38    ) -> DomRoot<BeforeUnloadEvent> {
39        reflect_dom_object(cx, Box::new(BeforeUnloadEvent::new_inherited()), window)
40    }
41
42    pub(crate) fn new(
43        cx: &mut JSContext,
44        window: &Window,
45        type_: Atom,
46        bubbles: EventBubbles,
47        cancelable: EventCancelable,
48    ) -> DomRoot<BeforeUnloadEvent> {
49        let ev = BeforeUnloadEvent::new_uninitialized(cx, window);
50        {
51            let event = ev.upcast::<Event>();
52            event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
53        }
54        ev
55    }
56}
57
58impl BeforeUnloadEventMethods<crate::DomTypeHolder> for BeforeUnloadEvent {
59    /// <https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue>
60    fn ReturnValue(&self) -> DOMString {
61        self.return_value.borrow().clone().root()
62    }
63
64    /// <https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue>
65    fn SetReturnValue(&self, value: DOMString) {
66        *self.return_value.borrow_mut() = value.traced();
67    }
68
69    /// <https://dom.spec.whatwg.org/#dom-event-istrusted>
70    fn IsTrusted(&self) -> bool {
71        self.event.IsTrusted()
72    }
73}