Skip to content

Instantly share code, notes, and snippets.

@vaebe
Created May 19, 2025 07:00
Show Gist options
  • Save vaebe/48cb0386e9387e04c6a6eceebd47e2b1 to your computer and use it in GitHub Desktop.
Save vaebe/48cb0386e9387e04c6a6eceebd47e2b1 to your computer and use it in GitHub Desktop.
vue3 组合式函数实现视频画中画
export function usePictureInPicture(domId: string) {
const getDom = () => document.getElementById(domId) as HTMLVideoElement
const isPipActive = ref(false)
async function enterPip() {
const videoDom = getDom()
if (videoDom) {
try {
await videoDom.requestPictureInPicture()
isPipActive.value = true
}
catch (err) {
console.error('Failed to enter PiP mode:', err)
}
}
}
async function exitPip() {
if (document.pictureInPictureElement) {
try {
await document.exitPictureInPicture()
isPipActive.value = false
}
catch (err) {
console.error('Failed to exit PiP mode:', err)
}
}
}
async function togglePip() {
if (isPipActive.value) {
await exitPip()
}
else {
await enterPip()
}
}
function handlePipChange() {
isPipActive.value = !!document.pictureInPictureElement
}
onMounted(() => {
document.addEventListener('enterpictureinpicture', handlePipChange)
document.addEventListener('leavepictureinpicture', handlePipChange)
})
onUnmounted(() => {
document.removeEventListener('enterpictureinpicture', handlePipChange)
document.removeEventListener('leavepictureinpicture', handlePipChange)
})
return { isPipActive, enterPip, exitPip, togglePip }
}
// 使用
const { togglePip } = usePictureInPicture(`${loginResData.value.id}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment