Automatic Material Dark-Mode for YouTube

A low-tech solution to a high-tech problem! Automatically clicks YouTube's "Dark Mode" button if dark mode isn't already active.

目前为 2017-09-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Automatic Material Dark-Mode for YouTube
  3. // @namespace SteveJobzniak
  4. // @version 1.4
  5. // @description A low-tech solution to a high-tech problem! Automatically clicks YouTube's "Dark Mode" button if dark mode isn't already active.
  6. // @author SteveJobzniak
  7. // @match *://www.youtube.com/*
  8. // @exclude *://www.youtube.com/tv*
  9. // @exclude *://www.youtube.com/embed/*
  10. // @run-at document-end
  11. // @grant none
  12. // @noframes
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17.  
  18. /* Performs multiple retries of a function call until it either succeeds or has failed all attempts. */
  19. function retryFnCall( fnCallback ) {
  20. // If we don't succeed immediately, we'll perform multiple retries.
  21. var success = fnCallback();
  22. if( ! success ) {
  23. var attempt = 0, maxAttempts = 40, waitDelay = 50; // 40 * 50ms = Max ~2 seconds of retries.
  24. var searchTimer = setInterval( function() {
  25. var success = fnCallback();
  26.  
  27. // If we've reached max attempts or found success, we must now stop the interval timer.
  28. if( ++attempt >= maxAttempts || success ) {
  29. clearInterval( searchTimer );
  30. }
  31. }, waitDelay );
  32. }
  33. }
  34.  
  35. /* Searches for a specific element. */
  36. function findElement( parentElem, elemQuery, expectedLength, selectItem, fnCallback ) {
  37. var elems = parentElem.querySelectorAll( elemQuery );
  38. if( elems.length === expectedLength ) {
  39. var item = elems[selectItem];
  40. fnCallback( item );
  41. return true;
  42. }
  43.  
  44. //console.log('Debug: Cannot find "'+elemQuery+'".');
  45. return false;
  46. }
  47.  
  48. function retryFindElement( parentElem, elemQuery, expectedLength, selectItem, fnCallback ) {
  49. // If we can't find the element immediately, we'll perform multiple retries.
  50. retryFnCall( function() {
  51. return findElement( parentElem, elemQuery, expectedLength, selectItem, fnCallback );
  52. } );
  53. }
  54.  
  55. /* Searches for multiple different elements and uses the earliest match. */
  56. function multiFindElement( queryList, fnCallback ) {
  57. for( var i=0, len=queryList.length; i<len; ++i ) {
  58. var query = queryList[i];
  59. var success = findElement( query.parentElem, query.elemQuery, query.expectedLength, query.selectItem, fnCallback );
  60. if( success ) {
  61. // Don't try any other queries, since we've found a successful match.
  62. return true;
  63. }
  64. }
  65.  
  66. return false;
  67. }
  68.  
  69. function retryMultiFindElement( queryList, fnCallback ) {
  70. // If we can't find any of the elements immediately, we'll perform multiple retries.
  71. retryFnCall( function() {
  72. return multiFindElement( queryList, fnCallback );
  73. } );
  74. }
  75.  
  76. /* Automatically enables YouTube's dark mode theme. */
  77. function enableDark() {
  78. // Wait until the settings menu is available, to ensure that YouTube's "dark mode state" and code has been loaded...
  79. // Note that this particular menu button always exists (both when logged in and when logged out of your account),
  80. // but its actual icon and the list of submenu choices differ. However, its "dark mode" submenus are the same in either case.
  81. retryFindElement( document, 'button.style-scope.ytd-topbar-menu-button-renderer', 2, 1, function( settingsMenuButton ) {
  82. // Check the dark mode state "flag" and abort processing if dark mode is already active.
  83. if( document.body.getAttribute( 'dark' ) === 'true' ) { return; }
  84.  
  85. // We MUST open the "settings" menu, otherwise nothing will react to the "toggle dark mode" event!
  86. settingsMenuButton.click();
  87.  
  88. // Wait a moment for the settings-menu to open up after clicking...
  89. retryFindElement( document, 'div#label.style-scope.ytd-toggle-theme-compact-link-renderer', 1, 0, function( darkModeSubMenuButton ) {
  90. // Next, go to the "toggle dark mode" settings sub-page.
  91. darkModeSubMenuButton.click();
  92.  
  93. // Wait a moment for the settings sub-page to switch...
  94. retryFindElement( document, 'ytd-toggle-item-renderer.style-scope.ytd-multi-page-menu-renderer', 1, 0, function( darkModeSubPageContainer ) {
  95. // Get a reference to the "activate dark mode" button...
  96. retryFindElement( darkModeSubPageContainer, 'paper-toggle-button.style-scope.ytd-toggle-item-renderer', 1, 0, function( darkModeButton ) {
  97. // We MUST now use this very ugly, hardcoded sleep-timer to ensure that YouTube's "activate dark mode" code is fully
  98. // loaded; otherwise, YouTube will be completely BUGGED OUT and WON'T save the fact that we've enabled dark mode!
  99. // Since JavaScript is single-threaded, this timeout simply ensures that we'll leave our current code so that we allow
  100. // YouTube's event handlers to deal with loading the settings-page, and then the timeout gives control back to us.
  101. setTimeout( function() {
  102. // Now simply click YouTube's button to enable their dark mode.
  103. darkModeButton.click();
  104.  
  105. // And lastly, give keyboard focus back to the input search field... (We don't need any setTimeout here...)
  106. retryFindElement( document, 'input#search', 1, 0, function( searchField ) {
  107. searchField.click(); // First, click the search-field to force the settings-panel to close...
  108. searchField.focus(); // ...and finally give the search-field focus! Voila!
  109. } );
  110. }, 20 ); // We can use 0ms here for "as soon as possible" instead, but our "at least 20ms" might be safer just in case.
  111. } );
  112. } );
  113. } );
  114. } );
  115.  
  116. // Alternative method, which switches using an internal YouTube event instead of clicking
  117. // the menus... I decided to disable this method, since it relies on intricate internal
  118. // details, and it still requires their menu to be open to work anyway (because their
  119. // code for changing theme isn't active until the Dark Mode settings menu is open),
  120. // so we may as well just click the actual menu items. ;-)
  121. /*
  122. var ytDebugMenu = document.querySelectorAll('ytd-debug-menu');
  123. ytDebugMenu = (ytDebugMenu.length === 1 ? ytDebugMenu[0] : undefined);
  124. if( ytDebugMenu ) {
  125. ytDebugMenu.fire(
  126. 'yt-action',
  127. {
  128. actionName:'yt-signal-action-toggle-dark-theme-on',
  129. optionalAction:false,
  130. args:[
  131. {signalAction:{signal:'TOGGLE_DARK_THEME_ON'}},
  132. toggleMenuElem,
  133. undefined
  134. ],
  135. returnValue: []
  136. },
  137. {}
  138. );
  139. }
  140. */
  141.  
  142. // Also note that it may be possible to simply modify the YouTube cookies, by changing
  143. // "PREF=f1=50000000;" to "PREF=f1=50000000&f6=400;" (dark mode on) and then reloading the page.
  144. // However, a reload is always slower than toggling the settings menu, so I didn't do that.
  145. }
  146.  
  147. if( document.readyState === 'complete' ) {
  148. enableDark();
  149. } else {
  150. document.addEventListener( 'readystatechange', function( evt ) {
  151. if( document.readyState === 'complete' ) {
  152. enableDark();
  153. }
  154. } );
  155. }
  156. })();