Youtube - Auto Like

Auto likes a video after watching it, the goal being to keep track of watched videos since youtube history is limited

当前为 2022-11-27 提交的版本,查看 最新版本

// ==UserScript==
// @name         Youtube - Auto Like
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Auto likes a video after watching it, the goal being to keep track of watched videos since youtube history is limited
// @author       You
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// @license      MIT
// ==/UserScript==


function l(...args){
    console.log('[Auto Like]', ...args)
}

function getLikeButton(){
    return document.querySelector('#segmented-like-button button')
}

function isLiked(){
    return getLikeButton().ariaPressed === 'true'
}

function like(){
    getLikeButton().click()
}


let ontimeupdate
function listen(){
    //Remove previous event listener since the video element is never destroyed
    if(ontimeupdate) video.removeEventListener('timeupdate', ontimeupdate)

    let video = document.querySelector('video')
    let watched = false
    ontimeupdate = () => {
        if(!watched){
            if(video.currentTime/video.duration > 0.95){
                watched = true
                like()
            }
        }
    }

    video.addEventListener('timeupdate', ontimeupdate)
}

let lastPage
const observer = new MutationObserver((mutationsList, observer) => {
    if(document.URL.includes('/watch')){
        //do something once per page
        if(lastPage !== document.URL){
            //keep trying to find the like button (page is loading)
            if(getLikeButton()){
                if(!isLiked()){
                    listen()
                }
                lastPage = document.URL
            }
        }
    }
})

observer.observe(document, {childList:true, subtree:true})