如何在 javascript 中将 mutationobserver 与 youtube spa 技术一起使用

how to use mutationobserver with youtube spa technology in javascript

我希望 YouTube 播放列表中的视频在达到我想要的第二个时转到下一个视频。但是我不能一直检查 location.href,我希望代码在再次打开相同的 url 时变为 运行,因为我循环播放列表。

const counterEle = document.querySelector("video");

function generateCount(limit) {
  mutation(160.510023);

  if (counterEle.currentTime > limit) {
    console.log("current > limit");
  } else {
    setTimeout(generateCount, 3000, limit);
    setTimeout(mutation, 3000, limit);
  }
}


let previousUrl = 'https://www.youtube.com/watch?v=93qE6Z8qheA&list=PL9dIg-VwAsxZdZvuHjzTOP8-49CWpis17&index=5';
const observer = new MutationObserver(mutation);

function mutation(limit) {
  generateCount(160.510023);
  if (location.href == previousUrl) {
    console.log(`URL changed to ${location.href}`);
    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();
    } else {
      setTimeout(generateCount, 3000);
    }
    } else {
      console.log("!=");
    }
}

我试了很多方法,我做错了什么?

(代码运行没有问题,只是检查域名有问题)

您可以在 video html 媒体元素上使用 ontimeupdate。这样,当当前时间发生变化时,您会收到通知。

您还可以使用 document.querySelector('.ad-interrupting')

检查广告是否正在播放

以下代码将在 5 秒后播放播放列表中的下一个元素:

const specificTime = 5; //play next after 5 seconds
const vid = document.querySelector("video");
vid.ontimeupdate = function onTimeUpdate(){
    var ad = document.querySelector('.ad-interrupting');
    if (!ad && vid.currentTime >= specificTime){
        console.log("playing next");
        document.querySelector(
            "#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button"
        ).click();
    }
}

Tampermonkey 脚本示例:

// ==UserScript==
// @name         autoplay next video in playslist
// @version      0.1
// @description  play next video in playlist after X seconds
// @include      /https:\/\/www\.youtube\.com\/watch?.*list=PL9dIg-VwAsxZdZvuHjzTOP8-49CWpis17.*/
// ==/UserScript==

(function() {
    'use strict';

    const specificTime = 5; //play next after 5 seconds
    const vid = document.querySelector("video");
    vid.ontimeupdate = function onTimeUpdate(){
        var ad = document.querySelector('.ad-interrupting');
        if (!ad && vid.currentTime >= specificTime){
            console.log("playing next");
            document.querySelector(
                "#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button"
            ).click();
        }
    }
})();

激活后匹配 this playlist