feat: 优化注入代码执行顺序 添加自定义注入标识

This commit is contained in:
Forget
2024-12-17 18:06:00 +08:00
parent f4ca2ca2df
commit bd07130fe1
3 changed files with 112 additions and 36 deletions
+2 -34
View File
@@ -1,6 +1,7 @@
import { useQuery } from "@tanstack/react-query"
import React, { useCallback, useEffect } from "react"
import React, { useEffect } from "react"
import { useTranslation } from "react-i18next"
import {InjectContext} from "./lib/inject"
import { Route, BrowserRouter as Router, Routes } from "react-router-dom"
import Footer from "./components/Footer"
@@ -21,39 +22,6 @@ const App: React.FC = () => {
})
const { i18n } = useTranslation()
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(() => {
if (settingData?.data?.custom_code) {