【问题标题】:Can't run function by checking domain无法通过检查域来运行功能
【发布时间】:2021-06-13 10:12:25
【问题描述】:

我希望 youtube 播放列表中的视频在到达 2:41 秒时跳到下一个视频。

单独运行域控制时有效,单独运行函数时有效。

它不能一起工作,为什么?我无法通过使用window.location.href 检查域来运行该功能。

function generateCount(limit) {
   const counterEle = document.querySelector("video");
   if (counterEle.currentTime > limit) {
        document
          .querySelector(
            "#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button"
          )
          .click();

        setInterval(generateCount, 3000, limit);
     }
}

if (
      window.location.href ==
      "https://www.youtube.com/watch?v=93qE6Z8qheA&list=PL9dIg-VwAsxZdZvuHjzTOP8-49CWpis17&index=5"
    ) {
      generateCount(160.510023);
}

【问题讨论】:

  • 可能是网址不正确?当我转到您的链接时,我会被退回到 index=6(虽然视频 ID 相同,但播放列表顺序可能已更改?)

标签: javascript function if-statement youtube


【解决方案1】:

当您第一次运行代码时,您会调用 generateCount(160.510023); 函数,该函数会检查视频的当前时间。如果这在您的页面最初加载时运行,则视频播放器的时间将小于160.510023,因此您的 if 语句条件将评估为false,您的脚本将完成。相反,请在页面加载时启动间隔计时器,而不是在移至下一个视频时启动。这样你就可以重复调用generateCount获取第一个视频,然后重复检查当前视频时间:

function generateCount(limit) {
  const counterEle = document.querySelector("video");
  if (counterEle.currentTime > limit) {
    document
      .querySelector(
        "#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button"
      )
      .click();
  }
}

if (window.location.href == "https://www.youtube.com/watch?v=93qE6Z8qheA&list=PL9dIg-VwAsxZdZvuHjzTOP8-49CWpis17&index=5") {
  setInterval(generateCount, 3000, 160.510023);
}

由于 youtube 是一个 SPA,即使在重定向到下一个视频之后,此代码也会运行。如果您只希望它为您的第一个视频运行,您可以在检查 url 的第一个 if 语句中正常调用 generatetCount() 函数,然后在 ~3s 后使用 setTimeout()generateCount() 的新呼叫进行排队如果当前时间小于(或等于)限制,则重新检查当前视频时间:

function generateCount(limit) {
  const counterEle = document.querySelector("video");
  if (counterEle.currentTime > limit) {
    ...
  } else {
    setTimeout(generateCount, 3000, limit);
  }
}

if (...) {
  generateCount(160.510023);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多