将youtube视频嵌入网络中,无法加载资源:net :: ERR_CONNECTION_CLOSED`

时间:2018-08-22 06:58:05

标签: javascript video youtube youtube-api embed

// 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();
}
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

将YouTube视频嵌入到网络中Failed to load resource: net::ERR_CONNECTION_CLOSED。我从youtube开发人员文档link复制了代码。但是我不知道为什么我会出错。但是我看到了这个演示link正在播放,我不明白为什么。还看到了这样的问题link,它在link中有一个演示也无法正常工作。

能不能指出我应该去哪里?

1 个答案:

答案 0 :(得分:0)

您已将代码括在右括号之间,如下所示,对吗?找不到错误。应该可以...

<script type="text/javascript">
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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '270',
width: '480',
videoId: 'nM82jzoJfjA',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done)
{
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
<div id="player"></div>