yew_hooks/hooks/
use_favicon.rs1use gloo::utils::document;
2use web_sys::{HtmlLinkElement, Node};
3
4use wasm_bindgen::{JsCast, UnwrapThrowExt};
5use yew::prelude::*;
6
7#[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}