Skip to content

Commit

Permalink
fix: 切换清晰度后无法正确监听video宽度变化
Browse files Browse the repository at this point in the history
  • Loading branch information
eeelester committed Oct 8, 2024
1 parent 0faf599 commit 8260dba
Showing 1 changed file with 51 additions and 3 deletions.
54 changes: 51 additions & 3 deletions entrypoints/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default defineContentScript({
let existElement: HTMLElement | null
let root: Root | null
let liveWS: LiveWS | null
let resizeObserver: ResizeObserver | null
let switchState: boolean = true
let isMount = false
let isFirst = true
Expand All @@ -39,18 +40,65 @@ export default defineContentScript({
true,
);

// 判断video出现的时机,没用mutationobserver是因为监听iframe里的节点麻烦
// video出现的时机
function loop() {
const video = getVideoDom()
if (video) {
listenVideoSizeChange(video)
// 如果切换清晰度,会销毁原本的video,然后新增video,所以原本在之前的video监听宽度已经没用了,需要重新监听
monitorVideo(video)
} else {
window.requestAnimationFrame(loop);
}
}

window.requestAnimationFrame(loop);

function monitorVideo(video){
const videoParent = video.parentNode

// 当观察到变动时执行的回调函数
const callback = function (mutationsList) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
for (const i of mutation.addedNodes) {
// 遍历新增的节点,取出新增的video节点
const addVideoDom = getAddVideoDom(i);
if(addVideoDom){
resizeObserver?.disconnect()
listenVideoSizeChange(addVideoDom)
}
}
}
}
};

// 创建一个观察器实例并传入回调函数
const observer = new MutationObserver(callback);

// 以上述配置开始观察目标节点
observer.observe(videoParent as Node, {
attributes: false,
childList: true,
subtree: true
});
}

function getAddVideoDom(dom: HTMLElement | ChildNode): false | HTMLVideoElement {
if (dom.nodeName === 'VIDEO') {
return dom as HTMLVideoElement;
}

for (const i of dom.childNodes) {
const iframeDom = getAddVideoDom(i);
if (iframeDom) {
return iframeDom;
}
}
return false;
}


function mount(log: string) {
if (isMount) return
isMount = true
Expand Down Expand Up @@ -92,7 +140,7 @@ export default defineContentScript({

function listenVideoSizeChange(video: HTMLVideoElement) {
let lastTimePageFullScreen = false
const resizeObserver = new ResizeObserver((entries) => {
resizeObserver = new ResizeObserver((entries) => {
// 当用户在popup关闭此功能后
if (!switchState)
return
Expand Down Expand Up @@ -157,7 +205,7 @@ export default defineContentScript({
})
}

// 获取跟video的父级dom(B站video的父级dom结构老是变,有病的!)
// 获取跟video的dom(B站video的父级dom结构老是变,有病的!)
function getVideoDom() {
return document.querySelector('video') || getVideoDomFromIframe()?.contentDocument?.querySelector('video')
}
Expand Down

0 comments on commit 8260dba

Please sign in to comment.