leitning
leitning

Reputation: 1506

Possible to add an onclick event to a YouTube iframe?

I've got a site with an HTML5 audio player and embedded YouTube music videos. I'd like to make it so that when the user clicks on a YouTube video to play it the music will stop. Wrapping the iframe in

<div id='vidWrapper' onclick='pauseAudio()'>YT stuff</div>

works for the sliver of pixels outside of the iframe, but not when you click on the actual video. Anyone have any ideas?

Upvotes: 4

Views: 15473

Answers (3)

Manthan Pawar
Manthan Pawar

Reputation: 1

Below is my whole source code for react-native-webview, it works for me:

source={{
  html: `<html><head><meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    img {width: ${screenWidth - 70}}
    ${customfonts.toString()}
    body{
      font-family: 'Segoe UI';
      font-size: ${fontScale * font14}px;
      color: ${colors.PLACEHOLDER_COLOR};
    }
    h4{
      font-size: ${fontScale * font18}px;
    }
  </style>
</head>
<body>

<script>
  // Callback function when the YouTube IFrame API is ready
  function onYouTubeIframeAPIReady() {
    var iframes = document.querySelectorAll('iframe');

    iframes.forEach(function(iframe) {
      var width = iframe.width;
      var height = iframe.height;
      var src = iframe.src;
      if(src?.toLowerCase()?.includes("youtube.com")){
        // Splitting to get the videoId from src.
        var partsArr = src.split('/');
        var videoSource = partsArr[partsArr.length - 1].split('?');

        var videoId = videoSource[videoSource.length - 2 ];

        // Create a new div to contain the player
        var div = document.createElement('div');
        div.id = 'player-' + videoId ? videoId : videoSource; // Unique ID for each player container
        iframe.parentNode.replaceChild(div, iframe);

        // Create the YouTube player
        new YT.Player(div.id, {
          height: 180,
          width: ${screenWidth - 70},
          videoId: videoId ? videoId : videoSource,
          events: {
            'onReady': function(event) {},
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                window.ReactNativeWebView.postMessage(JSON.stringify({height: document.body.scrollHeight,isPlaying: true, src: src}))
              }
            }
          }
        });
      }
    });
  }
</script>

<script>
  // Load the YouTube IFrame API script
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
${detailsData.description}
</body></html>`,
}}

Upvotes: -1

Nives pandey
Nives pandey

Reputation: 7

//More Refined Way to answer this question would be --
//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');
      }

Upvotes: 0

icaru12
icaru12

Reputation: 1582

You should use the YouTube IFrame API. Add an event listener for onStateChange to get notified when the player's state changes. See the sample code below.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://www.youtube.com/iframe_api"></script>
  </head>
  <body>
    <div id='vidWrapper'>
      <!-- The <iframe> (and video player) will replace this <div> tag. -->
      <div id="ytplayer"></div>
    </div>

    <script>
      var player;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('ytplayer', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                pauseAudio();
              }
            }
          }
        });
      }

      function pauseAudio() {
        ...
      }
    </script>
  </body>
</html>

Upvotes: 8

Related Questions