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