Youtube Resumer

Changes the ?t= parameter when pausing.

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

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