YouTube Better Window Title

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

当前为 2022-09-17 提交的版本,查看 最新版本

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