最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Play Youtube video on click - Stack Overflow

programmeradmin3浏览0评论

I'm using Youtube API, and have several Divs as thumbnails. When one thumbnail (div) is clicked, the corresponding Youtube video should play. I'm using an iframe element for the video, and the webpage is made up of only HTML, CSS and JavaScript. If I don't use a button (thumbnails/div with onclick) but rather have a blank page with the Youtube API JavaScript code, it'll work. However, when I try to wrap everything inside a function call (from the div's onclick) nothing happens, but I get this error.

"Refused to execute script from '' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."

Here is my code:

HTML:

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

JavaScript:

// 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "";
  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: 'M7lc1UVf-VE',
      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.PLAYING && !done) {
      //setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

This code is just copied from .

When this is all I have in the document, a player is there when the page loads, and the video is ready to play. So to clarify my question, how can I make it so that when a user clicks one of the buttons (div) the Youtube player displays and play the video?

I'm using Youtube API, and have several Divs as thumbnails. When one thumbnail (div) is clicked, the corresponding Youtube video should play. I'm using an iframe element for the video, and the webpage is made up of only HTML, CSS and JavaScript. If I don't use a button (thumbnails/div with onclick) but rather have a blank page with the Youtube API JavaScript code, it'll work. However, when I try to wrap everything inside a function call (from the div's onclick) nothing happens, but I get this error.

"Refused to execute script from 'https://www.youtube.com/embed/HVldRjNb4BE' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."

Here is my code:

HTML:

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

JavaScript:

// 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://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: 'M7lc1UVf-VE',
      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.PLAYING && !done) {
      //setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

This code is just copied from https://developers.google.com/youtube/iframe_api_reference.

When this is all I have in the document, a player is there when the page loads, and the video is ready to play. So to clarify my question, how can I make it so that when a user clicks one of the buttons (div) the Youtube player displays and play the video?

Share Improve this question asked Mar 10, 2017 at 6:44 FredFred 3972 gold badges5 silver badges18 bronze badges 1
  • can provide the html design for that – Amitesh Kumar Commented Mar 10, 2017 at 7:05
Add a comment  | 

2 Answers 2

Reset to default 15

Hello i think this will help you :

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Play Youtube Video On Click</title>
    </head>
    <body>
        <button onclick="myFunction();return false;">Click me</button>
        <div id="video"></div>

        <script>
            function myFunction() {
                document.getElementById("video").innerHTML = "<div id='player'></div>";

                // 2. This code loads the IFrame Player API code asynchronously.
                var tag = document.createElement('script');

                tag.src = "https://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: 'M7lc1UVf-VE',
                    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.PLAYING && !done) {
                    //setTimeout(stopVideo, 6000);
                    done = true;
                }
            }
            function stopVideo() {
                player.stopVideo();
            }
        </script>
    </body>
</html>

I realize this is an old thread, but it's a top search result on Google. A much simpler way to play a YouTube video in JavaScript is to change the src attribute of a YouTube Iframe object to include the ?autoplay=1 attribute.

JavaScript:

document.getElementById('my_youtube').src = 'https://www.youtube.com/embed/VIDEO_ID?autoplay=1'

HTML:

<iframe id="my_youtube" width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

The JavaScript code above can be added to an onclick handler.

发布评论

评论列表(0)

  1. 暂无评论