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