Skip to content

Commit 4e84f11

Browse files
committed
fix: 修复按钮卸载逻辑
如果将控制台切换到调试器面板时(需要开启会员) 提交按钮会被删除,取而代之的是调试按钮 之后切换会测试用例或代码执行结果时则会重新添加提交按钮 这时提交按钮已经变为新的,但扩展的计时功能却还是挂载在老的按钮上,导致计时功能失效 解决方案: 通过 MutationObserver 去监听提交按钮父节点的 childList 变更 在发现添加新的提交按钮时,将事件挂载到新的按钮上
1 parent ada87a8 commit 4e84f11

File tree

1 file changed

+47
-4
lines changed

1 file changed

+47
-4
lines changed

src/content/pages/problems/Clock.tsx

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -218,18 +218,61 @@ const Clock: FC = () => {
218218
}
219219

220220
void (async function () {
221-
const submitBtn = await findElement('.submit__-6u9')
221+
// 当前组件已经被卸载,就不需要挂载事件
222+
let submitBtn = await findElement('.submit__-6u9')
222223
const editEl = await findElement('.euyvu2f0')
223224

224-
// 当前组件已经被卸载,就不需要挂载事件
225+
const mount = async () => {
226+
submitBtn = await findElement('.submit__-6u9')
227+
if (cancel.current === 'unmount') return
228+
log.debug('挂载按钮')
229+
230+
submitBtn.addEventListener('click', handleClick)
231+
}
232+
233+
const unmount = async () => {
234+
log.debug('卸载按钮')
235+
submitBtn.removeEventListener('click', handleClick)
236+
}
237+
238+
const observer = new MutationObserver(function (
239+
mutationsList,
240+
_observer
241+
) {
242+
let isRemove = false,
243+
isAdd = false
244+
const check = (nodes: NodeList) =>
245+
Array.from(nodes).some(node =>
246+
(node as HTMLElement).classList.contains('submit__-6u9')
247+
)
248+
249+
for (const mutation of mutationsList) {
250+
if (mutation.type === 'childList') {
251+
if (check(mutation.removedNodes)) isRemove = true
252+
if (check(mutation.addedNodes)) isAdd = true
253+
}
254+
}
255+
if (isRemove) {
256+
// 删除提交按钮
257+
console.log('删除提交按钮')
258+
unmount()
259+
} else if (isAdd) {
260+
// 添加提交按钮
261+
console.log('添加提交按钮')
262+
mount()
263+
}
264+
})
265+
225266
if (cancel.current === 'unmount') return
226267

227-
submitBtn.addEventListener('click', handleClick)
268+
mount()
228269
editEl.addEventListener('keydown', handleKeydown, { capture: true })
270+
observer.observe(submitBtn.parentElement!, { childList: true })
229271

230272
cancel.current = () => {
231-
submitBtn.removeEventListener('click', handleClick)
273+
unmount()
232274
editEl.removeEventListener('keydown', handleKeydown, { capture: true })
275+
observer.disconnect()
233276
}
234277
})()
235278

0 commit comments

Comments
 (0)