Youtube Resumer

Updates the url so that it contains "?t={time}" corresponding to video.currentTime. Sometimes Youtube opens a video with a t parameter, but it doesn't get updated and when you refresh you go back to that time instead of where you left off.

当前为 2021-12-18 提交的版本,查看 最新版本

// ==UserScript==
// @name        Youtube Resumer
/* @description
Sometimes Youtube opens a video with a ?t= parameter, but it doesn't get updated and when you refresh you go back to that time instead of where you left off. Also, when reloading, it doesn't
resume exactly where you left off. This script updates the url each time you pause the video.

Feel free to use the timeupdate event instead of the pause event (floods browser history) or sessionStorage (the video loads at 0 and then moves to
video.currentTime = sessionStorage.getItem('seconds'), not as smooth as changing the url request).
*/
// @version     4
// @match       https://www.youtube.com/*
// @grant       none
// @namespace   https://greasyfork.org/users/206408
// @description Updates the url so that it contains "?t={time}" corresponding to video.currentTime. Sometimes Youtube opens a video with a t parameter, but it doesn't get updated and when you refresh you go back to that time instead of where you left off.
// ==/UserScript==

(async () => {

    function l(...args){
        console.log(`[Youtube Resumer]`, ...args)
    }

    function findVideo(){
        return document.querySelector('video')
    }

    //remove ?t=
    function cleanUrl(){
        const url = new URL(window.location.href)
        url.searchParams.delete('t')
        window.history.replaceState(null, null, url)
    }

    //update ?t=
    function changeUrl(time){
        const url = new URL(window.location.href)
        url.searchParams.set('t', time)
        window.history.replaceState(null, null, url)
    }

    function listen(){
        const video = findVideo()
        video.addEventListener('pause', () => {
            changeUrl(parseInt(video.currentTime))
        })
    }

    let listening = false //the video element exists even if you go back to the home page, so no need to readd event listeners

    //Event for each page change
    document.addEventListener("yt-navigate-finish", function() {
        l('navigate-finish')
        //Match page with video
        if(window.location.href.match(new RegExp('https://www.youtube.com/watch\\?v=.'))) {
            //Add video listener once
            if(!listening){
                l('listening')
                listen()
                listening = true
            }
        }
    });
})();