How to capture onclick within an iFrame for embedded YouTube video?

Viewed 15310

I have an iFrame that displays an embedded youtube video.

<iframe width="560" height="315" src="http://www.youtube.com/embed/xxx" frameborder="0" allowfullscreen></iframe>

What I would like to do is somehow capture the click event when the user clicks the you tube video so that I can call an http://myserver.com/dostuff rest api to update an external server counter tracking the number of clicks and of course allow the video to play as expected.

Any information would be greatly appreciated.

4 Answers
//Its possible by recording the stateChange in the video. 
//HTML code----

<!DOCTYPE html>
<html>
  <body>
    <div id='vidWrapper'>
    //your iframe tag goes here.
    <iframe id="video-id-first" src="https://www.youtube.com/embed/nNlEiuqiKAk?enablejsapi=1&amp;origin=http%3A%2F%2F3.7.232.244" gesture="media" allow="encrypted-media" allowfullscreen="" data-gtm-yt-inspected-53610233_3="true" width="560" height="400" frameborder="0"></iframe>
    </div>
   </body>
</html>

//JS code ----

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var width = document.getElementById("video-id-first").getAttribute("width");
var height = document.getElementById("video-id-first").getAttribute("height");
var src = document.getElementById("video-id-first").getAttribute("src");
//splitting to get the videoId from src.
var partsArr = src.split("/");
var videoSource = partsArr[partsArr.length -1 ].split("?");
var videoId = videoSource[videoSource.length -2 ];

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('vidWrapper', {
          height:height,
          width: width,
          videoId: videoId,
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                startVideo();
              }
                if (event.data == YT.PlayerState.PAUSED) {
                stopVideo();
              }
            }
          }
        });
      }
      function startVideo() {
      //write your functionality here.
        alert('Video Started');
      }
       function stopVideo() {
       //write your functionality here.
        alert('Video Paused');
      }
Related