yew_hooks/hooks/
use_before_unload.rs

1use web_sys::BeforeUnloadEvent;
2use yew::prelude::*;
3
4use super::use_event_with_window;
5
6/// A side-effect hook that shows browser alert when user try to reload or close the page.
7///
8/// # Example
9///
10/// ```rust
11/// # use yew::prelude::*;
12/// #
13/// use yew_hooks::prelude::*;
14///
15/// #[function_component(UseBeforeUnload)]
16/// fn before_unload() -> Html {
17///     use_before_unload(true, "You have unsaved changes, are you sure?".to_string());
18///     
19///     html! {
20///         <>
21///         </>
22///     }
23/// }
24/// ```
25#[hook]
26pub fn use_before_unload(enabled: bool, msg: String) {
27    use_event_with_window("beforeunload", move |e: BeforeUnloadEvent| {
28        if !enabled {
29            return;
30        }
31
32        if !msg.is_empty() {
33            e.set_return_value(msg.as_str());
34        }
35
36        // WebKit-derived browsers don't follow the spec for the dialog box.
37        // We should return msg in the future for the event handler.
38        // https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent
39    });
40}