Guard deferred video autoplay against slide changes
This commit is contained in:
+23
-14
@@ -167,21 +167,30 @@ export function initLightbox () {
|
|||||||
// fires contentActivate/contentDeactivate as slides become / stop being the
|
// fires contentActivate/contentDeactivate as slides become / stop being the
|
||||||
// current slide, including the initial slide on open.
|
// current slide, including the initial slide on open.
|
||||||
if (state.lightboxConfig.autoPlayVideos) {
|
if (state.lightboxConfig.autoPlayVideos) {
|
||||||
state.lightbox.on('contentActivate', ({ content }: { content: { element?: HTMLElement } }) => {
|
state.lightbox.on('contentActivate', ({ content }: { content: { element?: HTMLElement, slide?: { isActive: boolean } } }) => {
|
||||||
const video = content.element?.querySelector('video')
|
const video = content.element?.querySelector('video')
|
||||||
if (video) {
|
if (!video) return
|
||||||
setTimeout(() => {
|
// Brief delay so PhotoSwipe finishes attaching the video to the DOM
|
||||||
video.play().catch((err: Error) => {
|
// (deferred until the opening animation completes) - calling play()
|
||||||
// Only mute and retry if the browser explicitly blocked unmuted autoplay.
|
// synchronously gets interrupted by the attach and rejects with an
|
||||||
if (err.name === 'NotAllowedError') {
|
// AbortError.
|
||||||
video.muted = true
|
setTimeout(() => {
|
||||||
video.play().catch(() => {})
|
if (!content.slide?.isActive) return
|
||||||
} else if (err.name === 'AbortError') {
|
video.play().catch((err: Error) => {
|
||||||
video.play().catch(() => {})
|
if (err.name === 'NotAllowedError') {
|
||||||
}
|
// The browser blocked unmuted autoplay without a user gesture
|
||||||
})
|
// (e.g. a deep link straight to a video slide) - retry muted.
|
||||||
}, 50)
|
video.muted = true
|
||||||
}
|
video.play().catch(() => {})
|
||||||
|
} else if (err.name === 'AbortError' && content.slide?.isActive) {
|
||||||
|
// A pending play() was interrupted, e.g. by our contentDeactivate
|
||||||
|
// pause rejecting it while the video was still buffering. Only
|
||||||
|
// retry if the slide is still current, so we never resume audio
|
||||||
|
// behind a different slide.
|
||||||
|
video.play().catch(() => {})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}, 50)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user