函数内的YouTube API无法正常工作

时间:2018-09-06 23:10:50

标签: javascript

需要反复尝试并尝试在特定页面上加载YouTube视频,仅在桌面上加载并传递视频ID。因此,我必须将其投入使用。但是由于我无法理解的原因,我的尝试失败了,尝试了3天:)当您删除函数inyectYT(ytid)videoId: ytid并将其替换为下面的注释代码时,我的脚本有效。

确保它像往常一样简单,请看一看,谢谢。

console.clear();

function inyectYT(ytid) {
  var script = document.createElement("script");
  script.src = "https://www.youtube.com/iframe_api";
  var done = false;
  script.onload = script.onreadystatechange = function() {
    if (
      !done &&
      (!this.readyState ||
        this.readyState === "loaded" ||
        this.readyState === "complete")
    ) {
      done = true;
      script.onload = script.onreadystatechange = ytPlayerInit(ytid);
    }
  };
  document.getElementsByTagName("head")[0].appendChild(script);
}

function ytPlayerInit(ytid) {
  console.log(ytid);

  var playerOptions = {
    // Autoplay + mute has to be activated (value = 1) if you want to autoplay it everywhere
    // Chrome/Safari/Mobile
    autoplay: 1,
    mute: 1,
    autohide: 1,
    modestbranding: 1,
    rel: 0,
    showinfo: 0,
    controls: 0,
    disablekb: 1,
    enablejsapi: 1,
    iv_load_policy: 3,
    loop: 1
  };

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var ytPlayer;
  function onYouTubeIframeAPIReady(ytid) {
    ytPlayer = new YT.Player("player", {
      width: "1280",
      height: "720",
      videoId: ytid,
      //videoId: "M7lc1UVf-VE",
      playerVars: playerOptions,
      events: {
        onReady: onPlayerReady
        // 'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerReady(event) {
    event.target.playVideo();
  }
}

//dom ready

document.onreadystatechange = function() {
  if (
    document.readyState == "interactive" &&
    document.querySelector(".container").classList.contains("home")
  ) {
    inyectYT("M7lc1UVf-VE");
  }
};
  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
<div class="container home">
<div id="player"></div>
</div>  

1 个答案:

答案 0 :(得分:1)

此行有两个问题:

function onYouTubeIframeAPIReady(ytid) {

首先,在另一个函数内部声明一个函数只会使其在该外部函数中可访问。您从YouTube加载的代码无法找到。您可以通过将其附加到window对象来使其全局。

第二,当调用此函数时,它将不会收到ytid参数。您要做的是使用ytid收到的ytPlayerInit。您只需从onYouTubeIframeAPIReady删除参数(因为JS函数是闭包)。

这给了我们这一行:

window.onYouTubeIframeAPIReady = function () {

我也想指出

script.onload = script.onreadystatechange = ytPlayerInit(ytid);

等同于

ytPlayerInit(ytid);
script.onload = script.onreadystatechange = undefined;

({ytPlayerInit不返回值。)代码看起来像是您的意思

script.onload = script.onreadystatechange = function () {
  ytPlayerInit(ytid);
}

但是,那不是您当时想要在代码中执行的操作,而是您正在执行的操作。 (至少在我测试时。我不知道是否需要在那儿设置那些处理程序。)