Youtube Iframe can't work without refresh

Ant*_*e V 3 youtube-iframe-api angular

To reproduce the problem in Stackblitz, click GO to navigate to the component containing iframe, it works now, then go back and forward, the iframe disappears. You have to refresh the page to show the iframe again.

I tried some workaround :

  • I tried to release the object in ngOnDestroy window['onYouTubeIframeAPIReady'] = null; but not success

This is the code how to create iframe

init() {
  var tag = document.createElement('script');
  tag.src = 'https://www.youtube.com/iframe_api';
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}

ngOnInit() {
  this.init();
  window['onYouTubeIframeAPIReady'] = (e) => {
            this.YT = window['YT'];

            this.player = new window['YT'].Player('player', {
              videoId: '1cH2cerUpMQ'
            });
  };
}
Run Code Online (Sandbox Code Playgroud)

TEMPLATE

 <div id="player" >
 </div>
Run Code Online (Sandbox Code Playgroud)

Someone has a workaround with success please share, please.

yur*_*zui 5

您可以检查 youtube api 是否已经初始化,然后创建您的播放器:

player: any;

init() {
  if (window['YT']) {
    this.createPlayer();
    return;
  }

  var tag = document.createElement('script');
  tag.src = 'https://www.youtube.com/iframe_api';
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  window['onYouTubeIframeAPIReady'] = () => this.createPlayer();
}

ngOnInit() {
  this.init();
}

createPlayer() {
  this.player = new window['YT'].Player('player', {
    videoId: '1cH2cerUpMQ'
  });
}

ngOnDestroy() {
  window['onYouTubeIframeAPIReady'] = null;
  if (this.player) {
    this.player.destroy();
  }
}
Run Code Online (Sandbox Code Playgroud)

分叉的堆栈闪电战