summaryrefslogtreecommitdiff
path: root/youtube-auto-timestamper.user.js
blob: 490a2f663ebc73ab9557f01200dcc0374691a093 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// ==UserScript==
// @name        YouTube auto-timestamper
// @namespace   Violentmonkey Scripts
// @match       *://www.youtube.com/*
// @grant       none
// @version     1.2
// @author      -
// @description 12/17/2025, 5:12:31 PM
// ==/UserScript==


// interval in milliseconds
const interval = 1000;
// time before start in ms
const startDelay = 5000;
// regex used for determining url time
const timeRegex = /(([&?])t=[0-9]+)/
// negative time added to the url
const timeDelay = 0;
// how many seconds before the end do we mash the cancel autoplay button
const prefire = 5;

const tick = () => {
  const ytplayer = document.getElementById("movie_player");
  if (!ytplayer) {
    return
  }

  let shouldPreventAutoplay = false

  let time = ytplayer.getCurrentTime();
  time = Math.floor(time)

  if (time + prefire >= ytplayer.getDuration()) {
    shouldPreventAutoplay = true
  }

  time -= timeDelay

  if (time <= 0) {
    return
  }

  if (shouldPreventAutoplay) {
    document.querySelector("button[aria-label=\"Cancel autoplay\"]").click()
  }

  let currentUrl = window.location.href
  const baseUrl = window.location.href.replace(timeRegex, "")

  if (currentUrl.includes("t=")) {
    const match = currentUrl.match(timeRegex, "t=")
    currentUrl = currentUrl.replace(timeRegex, match[2] + "t=" + time)
  } else {
    currentUrl = currentUrl + "&t=" + time
  }


  history.replaceState(baseUrl, "", currentUrl)
}

console.debug(`autotimestamper will init in ${startDelay/1000}s`)


const script = setTimeout(() => {
  setInterval(tick, interval)
  console.debug("autotimestamper initialized")
}, startDelay)