YouTube Better Window Title

Add video length in minutes (rounded) and Channel Name to Window Title

  1. // ==UserScript==
  2. // @name YouTube Better Window Title
  3. // @namespace http://borisjoffe.com
  4. // @version 2.0.0
  5. // @description Add video length in minutes (rounded) and Channel Name to Window Title
  6. // @author Boris Joffe
  7. // @match https://*.youtube.com/*
  8. // @exclude https://accounts.youtube.com/RotateCookiesPage*
  9. // @exclude https://studio.youtube.com/persist_identity*
  10. // @grant unsafeWindow
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_deleteValue
  14. // @grant GM_listValues
  15. // @grant GM_registerMenuCommand
  16. // @license MIT
  17. // ==/UserScript==
  18.  
  19. /*
  20. The MIT License (MIT)
  21.  
  22. Copyright (c) 2018, 2020-2025 Boris Joffe
  23.  
  24. Permission is hereby granted, free of charge, to any person obtaining a copy
  25. of this software and associated documentation files (the "Software"), to deal
  26. in the Software without restriction, including without limitation the rights
  27. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  28. copies of the Software, and to permit persons to whom the Software is
  29. furnished to do so, subject to the following conditions:
  30.  
  31. The above copyright notice and this permission notice shall be included in
  32. all copies or substantial portions of the Software.
  33.  
  34. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  35. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  36. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  39. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40. THE SOFTWARE.
  41. */
  42.  
  43. /* jshint -W097, -W041 */
  44. /* eslint-disable no-console, no-unused-vars */
  45. 'use strict';
  46.  
  47. // skip inner frames: /persist_identity, /RotateCookiesPage, etc
  48. if (unsafeWindow.top !== unsafeWindow.self)
  49. return console.log('NOT in top frame - SKIP:', location.href)
  50.  
  51.  
  52. function onVideoPage() {
  53. // if (unsafeWindow.location.pathname === '/watch') dbg(new Date().getSeconds(), getWindowTitleRefresh()/1000, location.pathname)
  54. return unsafeWindow.location.pathname === '/watch'
  55.  
  56. // shorts have different HTML elements which need to be scraped separately. The globals with that data only work on the first video
  57. // || location.pathname.startsWith('/shorts')
  58.  
  59. // below is undefined when going to a non-watch page
  60. //&& unsafeWindow.ytInitialPlayerResponse
  61. }
  62.  
  63. // GM_deleteValue('titlerefresh')
  64. // GM_listValues()
  65. const DEFAULT_WINDOW_TITLE_REFRESH_MS = 4000
  66. const MINIMUM_WINDOW_TITLE_REFRESH_MS = 50
  67. function isValidTitleRefresh(val) { return val && val >= MINIMUM_WINDOW_TITLE_REFRESH_MS && isFinite(val) }
  68. function getWindowTitleRefresh() {
  69. const ms = JSON.parse(GM_getValue('titlerefresh', DEFAULT_WINDOW_TITLE_REFRESH_MS))
  70. if (isValidTitleRefresh(ms)) return ms
  71. else return DEFAULT_WINDOW_TITLE_REFRESH_MS
  72. }
  73. console.log('titlerefresh', getWindowTitleRefresh())
  74.  
  75. function getExpandComments() { return JSON.parse(GM_getValue('expandcomments', false)) }
  76. console.log('expandcomments', getExpandComments())
  77.  
  78. function getQuickReport() { return JSON.parse(GM_getValue('quickreport', false)) }
  79. console.log('quickreport', getQuickReport())
  80.  
  81. GM_registerMenuCommand("Set window title refresh interval", function() {
  82. var val = prompt("How often should the window title refresh?"
  83. + "\n\nDefault: " + DEFAULT_WINDOW_TITLE_REFRESH_MS + "ms (" + DEFAULT_WINDOW_TITLE_REFRESH_MS / 1000 + " seconds)"
  84. + "\nMinimum: " + MINIMUM_WINDOW_TITLE_REFRESH_MS + "ms (" + MINIMUM_WINDOW_TITLE_REFRESH_MS / 1000 + " seconds)"
  85. + "\nRecommended: 500-5000ms (0.5 - 5 seconds)"
  86. // + "\n\n1000 milliseconds = 1 second"
  87. + "\n\nCurrent value is listed below (in milliseconds)"
  88. , getWindowTitleRefresh())
  89.  
  90. if (val === null) alert('Cancelled. Refresh interval remains at ' + getWindowTitleRefresh() + 'ms')
  91. else if (isValidTitleRefresh(val)) GM_setValue("titlerefresh", JSON.parse(val));
  92. else alert('Invalid interval. Skipping setting titlerefresh')
  93. })
  94.  
  95. GM_registerMenuCommand("Set EXPAND_COMMENTS", function() {
  96. var val = prompt("Value for EXPAND_COMMENTS? (true or false) Current value is listed below", getExpandComments())
  97. GM_setValue("expandcomments", !!JSON.parse(val));
  98. })
  99.  
  100. GM_registerMenuCommand("Set QUICK_REPORT_COMMENT", function() {
  101. var val = prompt("Value for QUICK_REPORT_COMMENT? (true or false) Current value is listed below", getQuickReport())
  102. GM_setValue("quickreport", !!JSON.parse(val));
  103. })
  104.  
  105. // Util
  106. const DEBUG = false;
  107. function dbg() {
  108. if (DEBUG || JSON.parse(unsafeWindow.localStorage.getItem('DEBUG')))
  109. console.log.apply(console, ['DBG:', ...arguments])
  110.  
  111. return arguments[0];
  112. }
  113.  
  114.  
  115. var
  116. qs = document.querySelector.bind(document),
  117. qsa = document.querySelectorAll.bind(document),
  118. err = console.error.bind(console),
  119. log = console.log.bind(console),
  120. euc = encodeURIComponent;
  121.  
  122. function qsv(elmStr, parent) {
  123. var elm
  124. if (typeof parent === 'string') elm = qsv(parent).querySelector(elmStr)
  125. else if (typeof parent === 'object') elm = parent.querySelector(elmStr)
  126. else elm = qs(elmStr);
  127.  
  128. if (!elm) err('(qs) Could not get element -', elmStr);
  129. return elm;
  130. }
  131.  
  132. function qsav(elmStr, parent) {
  133. var elm
  134. if (typeof parent === 'string') elm = qsv(parent).querySelectorAll(elmStr)
  135. else if (typeof parent === 'object') elm = parent.querySelectorAll(elmStr)
  136. else elm = qsa(elmStr);
  137.  
  138. if (!elm) err('(qsa) Could not get element -', elmStr);
  139. return elm;
  140. }
  141.  
  142. function getProp(obj, path, defaultValue) {
  143. path = Array.isArray(path) ? Array.from(path) : path.split('.');
  144. var prop = obj;
  145.  
  146. while (path.length && obj) {
  147. prop = prop[path.shift()]
  148. }
  149.  
  150. return prop != null ? prop : defaultValue;
  151. }
  152.  
  153. function getWindowTitle() { return document.title; }
  154.  
  155. function setWindowTitle(newTitle) {
  156. document.title = newTitle;
  157. log('newTitle =', newTitle);
  158. }
  159.  
  160. function getVideoLengthSeconds() {
  161. // only works for first video
  162. // return getProp(unsafeWindow.ytplayer, 'config.args.length_seconds')
  163. // return unsafeWindow.ytInitialPlayerResponse.videoDetails.lengthSeconds;
  164.  
  165. return qsv('.ytp-progress-bar').getAttribute('aria-valuemax')
  166. }
  167.  
  168. function getVideoLengthFriendly() {
  169. // TODO: update
  170. return Math.round(getVideoLengthSeconds() / 60) + 'm';
  171. }
  172.  
  173. function getChannelName() {
  174. // only works for first video
  175. // return getProp(unsafeWindow.ytplayer, 'config.args.author')
  176. // return unsafeWindow.ytInitialPlayerResponse.videoDetails.author;
  177.  
  178. // WARNING: #channel-name is not a unique id
  179. return qsv('#below #channel-name a').innerText.replaceAll('\n', '').trim()
  180. }
  181.  
  182. function getChannelNameShort() {
  183. return getChannelName().substr(0, 20);
  184. }
  185.  
  186. function getVideoTitle() {
  187. // only works for first video
  188. // return getProp(unsafeWindow.ytplayer, 'config.args.title')
  189. // return unsafeWindow.ytInitialPlayerResponse.videoDetails.title;
  190.  
  191. return qsv('.title.ytd-video-primary-info-renderer').innerText
  192. }
  193.  
  194. function getVideoTitleShort() {
  195. return getVideoTitle()//.substr(0, 30);
  196. }
  197.  
  198. function updateWindowTitle() {
  199. var videoLength = getVideoLengthFriendly()
  200. var channelName = getChannelNameShort()
  201. var videoTitle = getVideoTitleShort()
  202.  
  203. // Don't duplicate channel name if it's part of the video title
  204. if (videoTitle.startsWith(channelName))
  205. videoTitle = videoTitle.substring(channelName.length)
  206. // Trim leading dashes e.g. often used as "<artist> - <title>"
  207. if (videoTitle.trim().startsWith('-'))
  208. videoTitle = videoTitle.trim().substring(1).trim()
  209.  
  210. setWindowTitle([videoLength + ',' + channelName, videoTitle].join('—'))
  211. return videoTitle
  212. // setTimeout(updateWindowTitle, getWindowTitleRefresh());
  213. }
  214.  
  215. function getVideoDate() {
  216. return getProp(qsv('#date'), 'innerText', '').trim() || qsv('meta[itemprop="uploadDate"]').getAttribute('content').split('T')[0]
  217. }
  218.  
  219. function getVideoYear() {
  220. const dateArr = getVideoDate().split(',')
  221. return dateArr[dateArr.length - 1].trim()
  222. }
  223.  
  224. function createWikiLink() {
  225. return '[[' + window.location.href + '|' + getVideoTitle() + ']] - '
  226. + getChannelName() + ', ' + getVideoYear() + ', ' + getVideoLengthFriendly()
  227. }
  228.  
  229. function $createWikiLink($ev) {
  230. /*
  231. qsv('#info.ytd-video-primary-info-renderer').lastChild.innerHTML +=
  232. '<div class="style-scope ytd-video-primary-info-renderer" style="color: white">'
  233. + createWikiLink()
  234. + '</div>'
  235. */
  236.  
  237. dbg('dblclick ev.target', $ev.target)
  238. if ($ev.target.tagName !== 'SPAN') {
  239. dbg('SKIPPING dblclick: ev target is not SPAN. Is:', $ev.target.tagName)
  240. return
  241. }
  242.  
  243. const isValidClassName = ['ytd-video-primary-info-renderer', 'yt-formatted-string']
  244. .filter(validClassName => $ev.target.className.includes(validClassName))
  245. .length
  246.  
  247. if (isValidClassName) {
  248. const wikiLink = createWikiLink()
  249. navigator.clipboard.writeText(wikiLink)
  250. log('DOUBLE CLICK: wiki link copied to clipboard:', wikiLink)
  251. } else {
  252. console.debug('SKIPPING dblclick: ev target is span, but not right class. Classes are:', $ev.target.className)
  253. }
  254. }
  255.  
  256.  
  257. function waitForLoad() {
  258. dbg('waitforload start', new Date().getSeconds(), '+', getWindowTitleRefresh() / 1e3, location.pathname)
  259.  
  260. setTimeout(waitForLoad, getWindowTitleRefresh())
  261.  
  262. if (!onVideoPage()) return dbg('skip waitforload. not on video page', unsafeWindow.location.href)
  263. // log('waitForLoad');
  264.  
  265. // if (! unsafeWindow.ytInitialPlayerResponse) {
  266. // log('waiting another 2 sec for ytInitialPlayerResponse')
  267. // setTimeout(waitForLoad, 2_000)
  268. // return;
  269. // }
  270.  
  271. //dbg('video details:', unsafeWindow.ytInitialPlayerResponse.videoDetails)
  272.  
  273. console.time('waitforload')
  274. // console.debug('video title =', getVideoTitleShort())
  275. updateWindowTitle()
  276.  
  277. // NOTE: some of these IDs are NOT unique on the page
  278. // const eventSelectors = ['#description-inner'/*, '#description', '#info-strings'*/]
  279. // eventSelectors
  280. // .map(selector => qsv(selector).addEventListener('dblclick', $createWikiLink, true))
  281. const $desc = qsv('#description-inner')
  282. $desc.removeEventListener('dblclick', $createWikiLink, true)
  283. $desc.addEventListener('dblclick', $createWikiLink, true)
  284.  
  285. console.timeEnd('waitforload')
  286. }
  287.  
  288. setInterval($clickReadMoreInComments, 10_000)
  289.  
  290. /** Click "Read More" to expand comments and expand replies to comments too */
  291. function $clickReadMoreInComments() {
  292. if (!getExpandComments() || !onVideoPage()) return
  293. qsav('.more-button').forEach(($btn) => $btn.checkVisibility() && $btn.click())
  294. }
  295.  
  296.  
  297. setInterval($quickReportComment, 5_000)
  298.  
  299. function handleDropdownClick(e) {
  300. setTimeout(() => {
  301. // click "Report"
  302. qsv('ytd-menu-popup-renderer yt-icon').click()
  303. // click Spam
  304. setTimeout(() =>
  305. Array.from(qsav('.YtRadioButtonItemViewModelLabel'))
  306. .filter(x => x.textContent.includes('Spam'))[0]
  307. .click()
  308. , 250)
  309. }, 250)
  310. }
  311.  
  312. // Click "Report" when clicking comment dropdown
  313. function $quickReportComment() {
  314. if (!getQuickReport() || !onVideoPage()) return
  315. const dropdownButtons = Array.from(qsav('.yt-icon-button'))
  316. dropdownButtons.map(btn => {
  317. btn.removeEventListener('click', handleDropdownClick)
  318. btn.addEventListener('click', handleDropdownClick)
  319. })
  320. // log('(YT Better Window Title) Added quickReportComment listener')
  321. }
  322.  
  323. setTimeout(waitForLoad, getWindowTitleRefresh());
  324.  
  325. // setTimeout(function () {
  326. // waitForLoad();
  327. // }, 6_000);
  328. // window eventListener doesn't work well for some reason
  329. // window.addEventListener('load', waitForLoad, true);
  330. // window.addEventListener('focus', waitForLoad, true);
  331. log('YouTube Better Window Title: started script')
  332.