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-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Youtube Resumer
  3. // @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.
  4. // @version 3
  5. // @match https://www.youtube.com/*
  6. // @grant none
  7. // @namespace https://greasyfork.org/users/206408
  8. // ==/UserScript==
  9.  
  10. (async () => {
  11.  
  12. function l(...args){
  13. console.log(`[Youtube Resumer]`, ...args)
  14. }
  15.  
  16. function tryListen(){
  17. const video = document.querySelector('video');
  18. if(video){
  19. l('listening', video)
  20. listening = true
  21. video.addEventListener('timeupdate', (event) => {
  22. const time = parseInt(video.currentTime)
  23. if(time > 0) { //avoid having ?t=0
  24. const url = new URL(window.location.href)
  25. url.searchParams.set('t', time)
  26. window.history.replaceState(null, null, url);
  27. }
  28. })
  29. }
  30. }
  31.  
  32. let listening = false //the video element exists even if you go back to the home page, so no need to readd event listeners
  33.  
  34. //Event for each page change
  35. document.addEventListener("yt-navigate-finish", function() {
  36. l('navigate-finish')
  37. if(!listening) tryListen()
  38. });
  39. })();