script/dom/
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 stylo_atoms::Atom;
7
8use crate::dom::bindings::cell::DomRefCell;
9use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
10use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
11use crate::dom::bindings::inheritance::Castable;
12use crate::dom::bindings::reflector::reflect_dom_object;
13use crate::dom::bindings::root::DomRoot;
14use crate::dom::bindings::str::DOMString;
15use crate::dom::event::{Event, EventBubbles, EventCancelable};
16use crate::dom::window::Window;
17use crate::script_runtime::CanGc;
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(window: &Window, can_gc: CanGc) -> DomRoot<BeforeUnloadEvent> {
35        reflect_dom_object(Box::new(BeforeUnloadEvent::new_inherited()), window, can_gc)
36    }
37
38    pub(crate) fn new(
39        window: &Window,
40        type_: Atom,
41        bubbles: EventBubbles,
42        cancelable: EventCancelable,
43        can_gc: CanGc,
44    ) -> DomRoot<BeforeUnloadEvent> {
45        let ev = BeforeUnloadEvent::new_uninitialized(window, can_gc);
46        {
47            let event = ev.upcast::<Event>();
48            event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
49        }
50        ev
51    }
52}
53
54impl BeforeUnloadEventMethods<crate::DomTypeHolder> for BeforeUnloadEvent {
55    /// <https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue>
56    fn ReturnValue(&self) -> DOMString {
57        self.return_value.borrow().clone()
58    }
59
60    /// <https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue>
61    fn SetReturnValue(&self, value: DOMString) {
62        *self.return_value.borrow_mut() = value;
63    }
64
65    /// <https://dom.spec.whatwg.org/#dom-event-istrusted>
66    fn IsTrusted(&self) -> bool {
67        self.event.IsTrusted()
68    }
69}