본문 바로가기
dev/webDev

youtube(유튜브) 동영상이 끝나면 실행되는 스크립트 만들기.

by Kelvin™ 2013. 3. 11.

동영상을 봐야지만 이벤트를 참가할수 있게 해주는 이벤트 생성시 유용하게 쓰일 수 있을 듯.


비메오도 해당 기능을 제공 하고 있슴.


뭐 찾으면 다 나올 듯.


아주 예전에 이벤트 했을때 이 기능이 없어서 다른 꼼수를 쓴듯 한데..



소스는 유튜브 개발자 페이지 레퍼런스를 아주 살짝 수정..




<!DOCTYPE html>

<html>

  <body>

    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->

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


    <script>

      // 2. This code loads the IFrame Player API code asynchronously.

      var tag = document.createElement('script');


      // This is a protocol-relative URL as described here:

      //     http://paulirish.com/2010/the-protocol-relative-url/

      // If you're testing a local page accessed via a file:/// URL, please set tag.src to

      //     "https://www.youtube.com/iframe_api" instead.

      tag.src = "//www.youtube.com/iframe_api";

      var firstScriptTag = document.getElementsByTagName('script')[0];

      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


      // 3. This function creates an <iframe> (and YouTube player)

      //    after the API code downloads.

      var player;

      function onYouTubeIframeAPIReady() {

        player = new YT.Player('player', {

          height: '390',

          width: '640',

          videoId: 'u1zgFlCw8Aw',

          events: {

            'onReady': onPlayerReady,

            'onStateChange': onPlayerStateChange

          }

        });

      }


      // 4. The API will call this function when the video player is ready.

      function onPlayerReady(event) {

        event.target.playVideo();

      }


      // 5. The API calls this function when the player's state changes.

      //    The function indicates that when playing a video (state=1),

      //    the player should play for six seconds and then stop.

      var done = false;

      function onPlayerStateChange(event) {

   // 동영상상태가 종료상태가 되면 구동.

        if (event.data == YT.PlayerState.ENDED) {

          alert("동영상 플레이가 종료되었습니다.");

        return;

        }

      }

      function stopVideo() {

        player.stopVideo();

      }

    </script>

  </body>

</html>