YouTube Better Window Title

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

当前为 2024-10-14 提交的版本,查看 最新版本

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