yew_hooks/hooks/
use_favicon.rs

1use gloo::utils::document;
2use web_sys::{HtmlLinkElement, Node};
3
4use wasm_bindgen::{JsCast, UnwrapThrowExt};
5use yew::prelude::*;
6
7/// A side-effect hook that sets favicon of the page.
8///
9/// # Example
10///
11/// ```rust
12/// # use yew::prelude::*;
13/// #
14/// use yew_hooks::prelude::*;
15///
16/// #[function_component(Favicon)]
17/// fn favicon() -> Html {
18///     use_favicon("https://crates.io/favicon.ico".to_string());
19///     
20///     html! {
21///         <>
22///         </>
23///     }
24/// }
25/// ```
26#[hook]
27pub fn use_favicon(href: String) {
28    use_effect_with(href, move |href| {
29        let link = {
30            if let Ok(Some(link)) = document().query_selector("link[rel*='icon']") {
31                link
32            } else {
33                document().create_element("link").unwrap_throw()
34            }
35        }
36        .dyn_into::<HtmlLinkElement>()
37        .unwrap_throw();
38
39        link.set_type("image/x-icon");
40        link.set_rel("shortcut icon");
41        link.set_href(href);
42
43        let head = document()
44            .get_elements_by_tag_name("head")
45            .item(0)
46            .unwrap_throw();
47        let _ = head.append_child(&link.dyn_into::<Node>().unwrap_throw());
48
49        || ()
50    });
51}