From f6bd831f0c006c64cbafa1f6832f92e55d812f80 Mon Sep 17 00:00:00 2001 From: John Smith Date: Sun, 4 May 2025 22:53:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=9C=89=E6=97=B6=E5=80=99?= =?UTF-8?q?=E6=B3=A8=E5=85=A5OBS=E4=B8=AD=E7=9A=84=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89CSS=E5=A4=B1=E8=B4=A5=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/views/Room.vue | 59 ++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/frontend/src/views/Room.vue b/frontend/src/views/Room.vue index 3b77ba5..39d37d4 100644 --- a/frontend/src/views/Room.vue +++ b/frontend/src/views/Room.vue @@ -54,9 +54,17 @@ class CustomTemplateRenderer { this._boundOnWindowMessage = this._onWindowMessage.bind(this) window.addEventListener('message', this._boundOnWindowMessage) + + this._connected = false + this._styleObserver = null } destroy() { + if (this._styleObserver) { + this._styleObserver.disconnect() + this._styleObserver = null + } + window.removeEventListener('message', this._boundOnWindowMessage) let dummyFunc = () => {} @@ -94,6 +102,12 @@ class CustomTemplateRenderer { let { type } = event.data switch (type) { case 'blcTemplateConnect': { + if (this._connected) { + console.warn('模板重复连接') + break + } + this._connected = true + // 发送初始化消息 let initData = { blcVersion: process.env.APP_VERSION, @@ -114,16 +128,7 @@ class CustomTemplateRenderer { } } - async _injectCss() { - if (document.readyState !== 'complete') { - // OBS的自定义CSS在load事件之后注入 - await new Promise(resolve => { - window.addEventListener('load', () => { - window.setTimeout(resolve, 100) - }) - }) - } - + _injectCss() { let injectCssUrls = [] if (this._config.importPresetCss) { injectCssUrls.push(window.location.origin + PRESET_CSS_URL) @@ -142,6 +147,40 @@ class CustomTemplateRenderer { injectCss: injectCssArr.join('\n\n'), }) } + + // OBS的自定义CSS可能在之后注入,再监听一段时间。OBS和直播姬都是注入到head的,如果有其他软件不是再改吧 + this._styleObserver = new MutationObserver(this._onDomMutate.bind(this)) + this._styleObserver.observe(document.head, { childList: true }) + window.setTimeout(() => { + if (this._styleObserver) { + this._styleObserver.disconnect() + this._styleObserver = null + } + }, 30 * 1000) + } + + _onDomMutate(mutations) { + let injectCssArr = [] + for (let mutation of mutations) { + if (mutation.type !== 'childList') { + continue + } + for (let el of mutation.addedNodes) { + if (el.nodeName !== 'STYLE') { + continue + } + if (el.textContent.indexOf(OBS_CSS_SIGN) !== -1) { + injectCssArr.push(el.textContent) + } + } + } + + if (injectCssArr.length !== 0) { + this._sendMessageToTemplate('blcInjectCss', { + injectCssUrls: [], + injectCss: injectCssArr.join('\n\n'), + }) + } } }