'e.target.playVideo does not play the video, but it plays it when I run it from the console

I'm using YouTube react library to play YouTube videos and control them via JS.

This is my component:

const VideoPage = ({ videoCode }) => {

    const onEnd = () => {
        document.location.reload()
    }

    const handleStateChange = e => {
        window.e = e
    }

    useEffect(() => {
        const interval = setInterval(() => {
            console.log('trying to play ...')
            if (window && window.e) {
                window.e.target.playVideo()
                clearInterval(interval)
            }
        }, 500)
    }, [])

    return <YouTube
        videoId={videoCode}
        opts={{
            height: '390',
            width: '640',
            playerVars: {
                autoplay: 1,
            },
        }}
        onStateChange={e => handleStateChange(e)}
        onEnd={() => onEnd()}
    />
}

export default VideoPage

No matter what I do, I can't autoplay the video. autoplay inside playerVars does not work. And I tried to call e.target.playVideo() from inside onStateChange and it does not work.

I also tried to set an interval. The code runs, but the video is not played and I see no error in console.

But when I run window.e.target.playVideo() from console, then video plays.

I'm getting crazy over this code. What should I do to fix this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source