Uriel
Uriel

Reputation: 37

how i can work the youtube api in my vue project?

Hi gangs actually I wont to use a youtube api inside my project but after that I put my script inside my index html and I put this code in my component

  methods: {
    onYouTubeIframeAPIReady() {
      window.player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        } 
    });

I have this errors YT is not defined no-undef

42:22 error 'initialize' is not defined.

Upvotes: 1

Views: 7944

Answers (3)

Maks Z.
Maks Z.

Reputation: 41

The reason why you have 'YT' undefined is either you have not included youtube script API or you are calling it without window.YT.

Here is a full implementation I have made.

<template>
  <div>
    <!-- This is the div where the IFrame API will inject the iframe content into -->
    <div id="main-video" class="main-video"></div>
    
    <button @click="play">Play</div>
  </div>
</template>

<script>
export default {
  name: 'MediaBlock',
  mounted() {
    this.mountYouTubeApi();
  },
  data() {
    return {
      player: null,
    };
  },
  methods: {
    mountYouTubeApi() {
       var firstScriptTag = document.getElementsByTagName('script')[0];

  /**
   * We do not want to include iframe_api script few times, when going back and force to page.
   * That's why we need to check if it has been already included.
   * If yes, we just need to create our player object, which will embed video on page.
   */
  if (!firstScriptTag.src.includes('youtube')) {
    /**
     * YouTube API
     *
     * Append youtube iFrame API from https://www.youtube.com/iframe_api
     * docs: https://developers.google.com/youtube/iframe_api_reference#Getting_Started
     */
    var tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    window.onYouTubeIframeAPIReady = this.initPlayer;
  } else {
    this.initPlayer();
  }
    },
    initPlayer() {
      const mainVideoEl = document.getElementById('main-video');
      this.player = new window.YT.Player(mainVideoEl, {
        width: '100%',
        height: 233,
        videoId: 'KJwYBJMSbPI',
        playerVars: { rel: 0 },
        events: {
          onReady: this.onInitialize()
        }
      });
    },
    onInitialize() {
      // console.log('YouTube video Initialized');
    },
    play() {
      this.player.playVideo();
    }
  }
};
</script>

Here you have also a custom "Play" button. Or you can use any other element to play your video.

onYouTubeIframeAPIReady is function, which runs when YouTube API is loaded. Then inside initPlayer you create a player with video defined in videoId.

Upvotes: 0

Kiran Parajuli
Kiran Parajuli

Reputation: 1045

The Youtube Iframe works slightly differently than you've implemented.

  1. First, you have to have the youtube iframe api script in your project index.html.

  2. Inside the component where you're trying use the iframe, implement the code like the following example:

<template>
<div class="playlist">
  <!-- this is the div where the IFrame API will inject the iframe content into -->
  <div id="video"></div>
</div>
</template>
<script>
export default {
  data() {
    return {
      player: null
    }
  }
  mounted() {
    window.onYouTubeIframeAPIReady = this.initPlayer
  },
  methods: {
    initPlayer() {
      const videoEl = document.getElementById("video")
      this.player = new YT.Player(videoEl, {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {},
        events: {
            onReady: this.onInitialize()
        } 
      });
    },
    onInitialize() { console.log("Initialized") }
  }
}
</script>

I've noticed you've used items like color and playlist in the playerVars option while creating the player. I am sorry, but these variables are not valid. You can see the available player variables options at https://developers.google.com/youtube/player_parameters

Here is an example component I have created for a similar use case. In the component, API loading is done using promises so you will never face issues like YT undefined. You can check it out at https://github.com/kiranparajuli589/vue3-ytframe/blob/master/lib/VueYtframe.vue Give it a star, if it helps :)

Upvotes: 1

balexandre
balexandre

Reputation: 75063

Welcome to StackOverflow!

You will have several issues with Youtube Player, but it's possible to work with it as long as you follow the strict rules

an error is to append onYouTubeIframeAPIReady() to anywhere that is not the window object, so you really need to start that function in the window, for example:

window.onYouTubeIframeAPIReady = () => {
  console.log("onYouTubeIframeAPIReady")
};

as you can't have this function inside a method, you can do the other way around... have that function call a method inside your Vue Object

var vueApp = new Vue({ 
  ...
  methods: {
    initYoutube() {}
  }
})

window.onYouTubeIframeAPIReady = () => {
  console.log("onYouTubeIframeAPIReady")
  vueApp.initYoutube()
};

and with that small trick you can use the Youtube API like normal:

<div id="app">
  <div id="player"></div>
</div>

var vueApp = new Vue({
  el: "#app",
  data: function () {
    return {
      player: null
    };
  },
  methods: {
    initYoutube() {
      const _ = this;
      console.log("initYoutube");
      this.player = new YT.Player("player", {
        width: 600,
        height: 400,
        videoId: "Xa0Q0J5tOP0",
        events: {
          onReady: _.onPlayerReady,
          onStateChange: _.onPlayerStateChange
        }
      });
    },
    onPlayerReady(evt) {
      console.log("Player ready");
      evt.target.playVideo();
    },
    onPlayerStateChange(evt) {
      console.log("Player state changed", evt);
    }
  }
});

onYouTubeIframeAPIReady = () => {
  console.log("onYouTubeIframeAPIReady");
  vueApp.initYoutube();
};

Here's a working example in CodePen

(sorry about Veutify, but my VueJs CodePen template set's all up automagically, just use without the vuetify: new Vuetify(), line) :)

Upvotes: 4

Related Questions