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

  1. // ==UserScript==
  2. // @name Youtube Resumer
  3. /* @description
  4. 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
  5. resume exactly where you left off. This script updates the url each time you pause the video.
  6.  
  7. 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
  8. video.currentTime = sessionStorage.getItem('seconds'), not as smooth as changing the url request).
  9. */
  10. // @version 4
  11. // @match https://www.youtube.com/*
  12. // @grant none
  13. // @namespace https://greasyfork.org/users/206408
  14. // @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.
  15. // ==/UserScript==
  16.  
  17. (async () => {
  18.  
  19. function l(...args){
  20. console.log(`[Youtube Resumer]`, ...args)
  21. }
  22.  
  23. function findVideo(){
  24. return document.querySelector('video')
  25. }
  26.  
  27. //remove ?t=
  28. function cleanUrl(){
  29. const url = new URL(window.location.href)
  30. url.searchParams.delete('t')
  31. window.history.replaceState(null, null, url)
  32. }
  33.  
  34. //update ?t=
  35. function changeUrl(time){
  36. const url = new URL(window.location.href)
  37. url.searchParams.set('t', time)
  38. window.history.replaceState(null, null, url)
  39. }
  40.  
  41. function listen(){
  42. const video = findVideo()
  43. video.addEventListener('pause', () => {
  44. changeUrl(parseInt(video.currentTime))
  45. })
  46. }
  47.  
  48. let listening = false //the video element exists even if you go back to the home page, so no need to readd event listeners
  49.  
  50. //Event for each page change
  51. document.addEventListener("yt-navigate-finish", function() {
  52. l('navigate-finish')
  53. //Match page with video
  54. if(window.location.href.match(new RegExp('https://www.youtube.com/watch\\?v=.'))) {
  55. //Add video listener once
  56. if(!listening){
  57. l('listening')
  58. listen()
  59. listening = true
  60. }
  61. }
  62. });
  63. })();