I’m using reactjs and for some reason, videos are not autoplaying on mobile.
I’m using iOS 17, Safari
Here is my code:
<div className="video" ref={videoRef} dangerouslySetInnerHTML={{
__html: `
<video
loop
muted
autoplay
playsinline
muted
defaultMuted
loop
>
<source src=${video} type="video/mp4" />
</video>
`}}>
On mobile, there is just a play button.
I also tried to play the video using javascript:
const videoRef = useRef(null)
useEffect(() => {
if (videoRef.current) {
const videoElement = videoRef.current.children[0];
videoElement.play();
}
})
However, I get the error: `The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission =.“`
2
Answers
Autoplay policies on mobile browsers, especially Safari on iOS, can be quite challenging due to user experience and data consumption considerations. To address this, browsers typically require user interaction before allowing autoplay.
you’re facing this issue due to autoplay is not allowed without user interaction on mobile devices. The attempt to play the video using JavaScript won’t work unless a user interaction event triggered .so
play
method should be triggered in response to a user interaction, like a button click or so , something likeanother solution would be using the
playsinline
attribute due to Safari on iOS has a requirement that videos must be played inline. make sure that you included this attribute in your video tagAnother solation if above didn’t work for anyone , we can try to play the video component mounted via
useEffect
hook by passing an Empty dependency array to ensure that it runs only once on mount also I’ve combined timeout func to come around the browser restriction especially on mobile devices , I’ll will explain Now By delaying theplay()
method with a timeout, you like creating a small window after the initial render during which theplay()
method is called. This is essentially simulating user interaction, allowing the video to start playing.In Some mobile devices,
autoplay
is only allowed if the video is triggered by a user interaction, such as a tap. Therefore, you can use a button or other UI element to start the video. Further, you can align its CSS classdisplay:none
So there is no button visible.