YouTube Better Window Title

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

当前为 2024-01-03 提交的版本,查看 最新版本

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