Skip to content

Commit 86c477a

Browse files
committed
✨ 优化自定义 js 功能,适配性更强。可自动识别加 <script> 和不加的情况。
1 parent a2ca40f commit 86c477a

File tree

1 file changed

+37
-6
lines changed

1 file changed

+37
-6
lines changed

src/components/layout/Header.vue

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -216,17 +216,48 @@ if (storageConfigStore.globalConfig.customCss) {
216216
console.error('加载自定义 css 加载失败:', storageConfigStore.globalConfig.customCss, e);
217217
}
218218
}
219+
import {Parser} from 'htmlparser2';
220+
221+
const loadScript = (script) => {
222+
if (script) {
223+
document.getElementsByTagName('head')[0].appendChild(script);
224+
console.debug(`加载自定义 js, src:${script.src}, text:${script.text}`);
225+
}
226+
}
219227
220228
onMounted(() => {
221229
nextTick(()=>{
222230
if (storageConfigStore.globalConfig.customJs) {
231+
let script = null;
223232
try {
224-
let clearCustomJs = storageConfigStore.globalConfig.customJs.replace(/<script.*?>|<\/script>/ig, "");
225-
console.log('加载自定义 js:', clearCustomJs);
226-
let script = document.createElement("script");
227-
script.type = "text/javascript";
228-
script.text = clearCustomJs;
229-
document.getElementsByTagName('head')[0].appendChild(script);
233+
const parser = new Parser({
234+
onopentag(name, attributes) {
235+
loadScript(script);
236+
if (name === "script") {
237+
script = document.createElement("script");
238+
for (let prop in attributes) {
239+
script[prop] = attributes[prop];
240+
}
241+
}
242+
},
243+
ontext(text) {
244+
if (!script) {
245+
script = document.createElement("script");
246+
}
247+
script.text = text;
248+
},
249+
onclosetag(tagname) {
250+
if (tagname === "script") {
251+
loadScript(script);
252+
script = null;
253+
}
254+
},
255+
onend() {
256+
loadScript(script);
257+
}
258+
});
259+
parser.write(storageConfigStore.globalConfig.customJs);
260+
parser.end();
230261
} catch (e) {
231262
console.log('加载自定义 js 失败: ', storageConfigStore.globalConfig.customJs, e);
232263
}

0 commit comments

Comments
 (0)