Cannot destroy youtube embedded video player

I am not able to destroy embedded youtube video on plyr player. player.destroy() method is called without any error but it does not destroy the player.

For this reason when I try to open another embedded video, it just loads the previous embedded video.

When I checked isEmbed property of the player it returns false. It should be true as I am playing youtube video.

I am using react js.

let video = document.getElementById('player-embed');

var youtubeEmbedId = extractYoutubeEmbedId(options.source.src)
window.player = new Plyr(video, defaultOptions);

useEffect(() => {

    return () => {
        window.player.destroy();
        if (window.hls) {
            window.destroyHLS();
        }
    }
}, [])

return (
    <div id="player-embed" data-plyr-provider="youtube" data-plyr-embed-id={youtubeEmbedId}/>
);

I found this codepen example for plyr youtube video example and it is working as expected. isEmbed property returns true and player.destroy() method indeed destroy the player. Don't know why it's not working for me.

1 answer

  • answered 2022-05-04 11:11 Dainius Lukša

    It seems like window.player = new Plyr() is called everytime your react component is rerendered, therefore you keep creating new Plyr instances. Try moving Plyr initialization to useState like const [player] = useState(new Plyr()) and then assign it to window in useEffect so it would get called only once.

    It still might have some bugs so you would be better off using Plyr official package for react https://github.com/chintan9/plyr-react

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum