diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 8fdb4d1..3addd6e 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -4,7 +4,7 @@ import { Skeleton } from "@/components/ui/skeleton"; import { fetchLoginUser, fetchSetting } from "@/lib/nezha-api"; import { useQuery } from "@tanstack/react-query"; import { DateTime } from "luxon"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useRef, useState, useCallback } from "react"; import { LanguageSwitcher } from "./LanguageSwitcher"; import { useTranslation } from "react-i18next"; import { useNavigate } from "react-router-dom"; @@ -22,10 +22,52 @@ function Header() { const siteName = settingData?.data?.site_name; + const InjectContext = useCallback((content: string) => { + const tempDiv = document.createElement("div"); + tempDiv.innerHTML = content; + + const handlers: { [key: string]: (element: HTMLElement) => void } = { + SCRIPT: (element) => { + const script = document.createElement("script"); + if ((element as HTMLScriptElement).src) { + script.src = (element as HTMLScriptElement).src; + } else { + script.textContent = element.textContent; + } + document.body.appendChild(script); + }, + STYLE: (element) => { + const style = document.createElement("style"); + style.textContent = element.textContent; + document.head.appendChild(style); + }, + DEFAULT: (element) => { + document.body.appendChild(element); + }, + }; + + Array.from(tempDiv.childNodes).forEach((node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + const element = node as HTMLElement; + (handlers[element.tagName] || handlers.DEFAULT)(element); + } else if (node.nodeType === Node.TEXT_NODE) { + document.body.appendChild( + document.createTextNode(node.textContent || "") + ); + } + }); + }, []); + useEffect(() => { document.title = siteName || "NEZHA"; }, [siteName]); + useEffect(() => { + if (settingData?.data?.custom_code) { + InjectContext(settingData?.data?.custom_code); + } + }, [settingData?.data?.custom_code]); + return (
@@ -113,7 +155,7 @@ function Overview() { const timeOption = DateTime.TIME_SIMPLE; timeOption.hour12 = true; const [timeString, setTimeString] = useState( - DateTime.now().setLocale("en-US").toLocaleString(timeOption), + DateTime.now().setLocale("en-US").toLocaleString(timeOption) ); useInterval(() => { setTimeString(DateTime.now().setLocale("en-US").toLocaleString(timeOption));