Disable YouTube Music AutoPause

「影片已暫停,要繼續觀賞嗎?」和「你還在螢幕前嗎?影片即將暫停播放」不再顯示。

目前為 2023-09-28 提交的版本,檢視 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name Disable YouTube Music AutoPause
  28. // @name:en Disable YouTube Music AutoPause
  29. // @name:ja Disable YouTube Music AutoPause
  30. // @name:zh-TW Disable YouTube Music AutoPause
  31. // @name:zh-CN Disable YouTube Music AutoPause
  32. // @namespace http://tampermonkey.net/
  33. // @version 2023.09.28.1
  34. // @license MIT License
  35. // @description "Video paused. Continue watching?" and "Still watching? Video will pause soon" will not appear anymore.
  36. // @description:en "Video paused. Continue watching?" and "Still watching? Video will pause soon" will not appear anymore.
  37. // @description:ja 「動画が一時停止されました。続きを視聴しますか?」と「視聴を続けていますか?動画がまもなく一時停止されます」は二度と起こりません。
  38. // @description:zh-TW 「影片已暫停,要繼續觀賞嗎?」和「你還在螢幕前嗎?影片即將暫停播放」不再顯示。
  39. // @description:zh-CN 「视频已暂停。是否继续观看?」和「仍在观看?视频即将暂停」不再显示。
  40. // @author CY Fung
  41. // @match https://music.youtube.com/*
  42. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  43. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/disable-youtube-autopause.svg
  44. // @supportURL https://github.com/cyfung1031/userscript-supports
  45. // @run-at document-start
  46. // @grant none
  47. // @unwrap
  48. // @allFrames true
  49. // @inject-into page
  50. // ==/UserScript==
  51.  
  52. /* jshint esversion:8 */
  53.  
  54. (function (__Promise__) {
  55. 'use strict';
  56.  
  57. /** @type {globalThis.PromiseConstructor} */
  58. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  59.  
  60. const youThereDataHashMapPauseDelay = new WeakMap();
  61. const youThereDataHashMapPromptDelay = new WeakMap();
  62. const youThereDataHashMapLactThreshold = new WeakMap();
  63. const websiteName = 'YouTube Music';
  64. let noDelayLogUntil = 0;
  65.  
  66. function delayLog(...args) {
  67. if (Date.now() < noDelayLogUntil) return;
  68. noDelayLogUntil = Date.now() + 280; // avoid duplicated delay log in the same time ticker
  69. console.log(...args);
  70. }
  71.  
  72. function defineProp1(youThereData, key, retType, constVal, fGet, fSet, hashMap) {
  73. Object.defineProperty(youThereData, key, {
  74. enumerable: true,
  75. configurable: true,
  76. get() {
  77. Promise.resolve(new Date).then(fGet).catch(console.warn);
  78. let ret = constVal;
  79. if (retType === 2) return `${ret}`;
  80. return ret;
  81. },
  82. set(newValue) {
  83. let oldValue = hashMap.get(this);
  84. Promise.resolve([oldValue, newValue, new Date]).then(fSet).catch(console.warn);
  85. hashMap.set(this, newValue);
  86. return true;
  87. }
  88. });
  89. }
  90.  
  91. function defineProp2(youThereData, key, qKey) {
  92. Object.defineProperty(youThereData, key, {
  93. enumerable: true,
  94. configurable: true,
  95. get() {
  96. const r = this[qKey];
  97. if ((r || 0).length >= 1) r.length = 0;
  98. return r;
  99. },
  100. set(nv) {
  101. return true;
  102. }
  103. });
  104. }
  105.  
  106. function hookYouThereData(youThereData) {
  107. if (!youThereData || youThereDataHashMapPauseDelay.has(youThereData)) return;
  108. const retPauseDelay = youThereData.playbackPauseDelayMs;
  109. const retPromptDelay = youThereData.promptDelaySec;
  110. const retLactThreshold = youThereData.lactThresholdMs;
  111. const tenPU = Math.floor(Number.MAX_SAFE_INTEGER * 0.1);
  112. const mPU = Math.floor(tenPU / 1000);
  113.  
  114. if ('playbackPauseDelayMs' in youThereData && retPauseDelay >= 0 && retPauseDelay < 4 * tenPU) {
  115. youThereDataHashMapPauseDelay.set(youThereData, retPauseDelay);
  116. const retType = typeof retPauseDelay === 'string' ? 2 : +(typeof retPauseDelay === 'number');
  117. if (retType >= 1) {
  118. defineProp1(youThereData, 'playbackPauseDelayMs', retType, 5 * tenPU, d => {
  119. delayLog(`${websiteName} is trying to pause video...`, d.toLocaleTimeString());
  120. }, args => {
  121. const [oldValue, newValue, d] = args;
  122. console.log(`${websiteName} is trying to change value 'playbackPauseDelayMs' from ${oldValue} to ${newValue} ...`, d.toLocaleTimeString());
  123. }, youThereDataHashMapPauseDelay);
  124. }
  125. if (typeof ((youThereData.showPausedActions || 0).length) === 'number' && !youThereData.tvTyh) {
  126. youThereData.tvTyh = [];
  127. defineProp2(youThereData, 'showPausedActions', 'tvTyh');
  128. }
  129. }
  130.  
  131. if ('promptDelaySec' in youThereData && retPromptDelay >= 0 && retPromptDelay < 4 * mPU) {
  132. youThereDataHashMapPromptDelay.set(youThereData, retPromptDelay);
  133. const retType = typeof retPromptDelay === 'string' ? 2 : +(typeof retPromptDelay === 'number');
  134. // lact -> promptDelaySec -> showDialog -> playbackPauseDelayMs -> pause
  135. if (retType >= 1) {
  136. defineProp1(youThereData, 'promptDelaySec', retType, 5 * mPU, d => {
  137. delayLog(`${websiteName} is trying to pause video...`, d.toLocaleTimeString());
  138. }, args => {
  139. const [oldValue, newValue, d] = args;
  140. console.log(`${websiteName} is trying to change value 'promptDelaySec' from ${oldValue} to ${newValue} ...`, d.toLocaleTimeString());
  141. }, youThereDataHashMapPromptDelay);
  142.  
  143. }
  144. }
  145.  
  146. if ('lactThresholdMs' in youThereData && retLactThreshold >= 0 && retLactThreshold < 4 * tenPU) {
  147. youThereDataHashMapLactThreshold.set(youThereData, retLactThreshold);
  148. const retType = typeof retLactThreshold === 'string' ? 2 : +(typeof retLactThreshold === 'number');
  149. // lact -> promptDelaySec -> showDialog -> playbackPauseDelayMs -> pause
  150. if (retType >= 1) {
  151. defineProp1(youThereData, 'lactThresholdMs', retType, 5 * tenPU, d => {
  152. // console.log(`${websiteName} is trying to pause video...`, d.toLocaleTimeString());
  153. }, args => {
  154. const [oldValue, newValue, d] = args;
  155. console.log(`${websiteName} is trying to change value 'lactThresholdMs' from ${oldValue} to ${newValue} ...`, d.toLocaleTimeString());
  156. }, youThereDataHashMapLactThreshold);
  157. }
  158. }
  159.  
  160. }
  161.  
  162. let symbol877 = Symbol();
  163.  
  164. // e.performDataUpdate -> f.playerData = a.playerResponse;
  165. // youthereDataChanged_(playerData.messages)
  166. // youthereDataChanged_ -> b.youThereRenderer && fFb(this.youThereManager_, b.youThereRenderer)
  167. // a.youThereData_ = b.configData.youThereData;
  168. // a.youThereData_.playbackPauseDelayMs
  169.  
  170. let psChangeRid = 0;
  171.  
  172. function onPlayerStateChange(evtValue) {
  173. if (evtValue == 1 || evtValue == 3) { // the event is just the state value
  174. // this is after getPlayerState()
  175. // in case youThereData is added after onPlayerStateChange
  176. if (psChangeRid > 1e9) psChangeRid = 9;
  177. let tid = psChangeRid;
  178. requestAnimationFrame(() => { // assume no update of messages in background; delayed to save processing energy
  179. if (tid !== psChangeRid) return;
  180. messageHook();
  181. });
  182.  
  183. }
  184. }
  185.  
  186. function messageHook() {
  187.  
  188. let messages = null;
  189. const playerElm = document.querySelector('#player') || 0;
  190. try {
  191. messages = ((playerElm.inst || 0).__data || playerElm.__data || 0).playerResponse_.messages;
  192. } catch (e) { }
  193. if (messages && messages.length > 0) {
  194. for (const message of messages) {
  195. if (message.youThereRenderer) {
  196. let youThereData = null;
  197. try {
  198. youThereData = message.youThereRenderer.configData.youThereData;
  199. } catch (e) { }
  200. if (youThereData) hookYouThereData(youThereData);
  201. youThereData = null;
  202. break;
  203. }
  204. }
  205. }
  206.  
  207. }
  208.  
  209.  
  210. let messagesRunnerRid = 0;
  211.  
  212. function messagesRunner() {
  213.  
  214.  
  215. messageHook();
  216.  
  217. /*
  218.  
  219. , fhb = function(a, b) {
  220. a.reset();
  221. if (1 === a.JSC$10962_playerApi.getPlayerState() || 3 === a.JSC$10962_playerApi.getPlayerState())
  222. if (a.youThereData = Fa("configData.youThereData", b),
  223. a.youThereData) {
  224. var c = a.JSC$10962_playerApi.getCurrentTime();
  225. a.showPromptJobId = mp(0, function() {
  226. ghb(a, b)
  227. }, 1E3 * Math.max((a.youThereData.promptDelaySec || 0) - c, 0))
  228. }
  229. }
  230.  
  231. */
  232.  
  233. const playerElm = document.querySelector('#player') || 0;
  234. const playerApi = (playerElm.inst || 0).playerApi_ || playerElm.playerApi_ || (playerElm.inst || 0).playerApi || playerElm.playerApi || 0;
  235. if (typeof playerApi === 'object') {
  236.  
  237. if (typeof playerApi[symbol877] === 'undefined' && typeof playerApi.getPlayerState === 'function') {
  238. playerApi[symbol877] = playerApi.getPlayerState;
  239. playerApi.getPlayerState = function () {
  240. let res = this[symbol877](...arguments);
  241. if (res == 1 || res == 3) {
  242. try {
  243. messageHook();
  244. } catch (e) { }
  245. }
  246. return res;
  247. };
  248. }
  249. if ('removeEventListener' in playerApi && 'addEventListener' in playerApi) {
  250. playerApi.removeEventListener("onStateChange", onPlayerStateChange, false);
  251. playerApi.addEventListener("onStateChange", onPlayerStateChange, false);
  252. }
  253. }
  254.  
  255. }
  256.  
  257.  
  258. async function canplayHandlerAsync() {
  259. noDelayLogUntil = Date.now() + 3400; // no delay log for video changes
  260.  
  261. messagesRunnerRid++;
  262. let tid = messagesRunnerRid;
  263. if (messagesRunnerRid > 1e9) messagesRunnerRid = 9;
  264.  
  265. await Promise.resolve(0);
  266. if (tid !== messagesRunnerRid) return;
  267. messagesRunner();
  268.  
  269. // run at 3.2s and 8.6s to ensure the page update is finished.
  270. // avoid duplicated calls if canplay is called more than one time (page is rapidly changing)
  271. await new Promise(r => setTimeout(r, 3200));
  272. if (tid !== messagesRunnerRid) return;
  273. messagesRunner();
  274.  
  275. await new Promise(r => setTimeout(r, 5400));
  276. if (tid !== messagesRunnerRid) return;
  277. messagesRunner();
  278.  
  279. }
  280.  
  281. function canplayHandler(evt) {
  282. if (evt.target.nodeName != 'VIDEO') return;
  283. if (!evt.target.closest('#player')) return;
  284. canplayHandlerAsync();
  285. }
  286.  
  287. document.addEventListener('canplay', canplayHandler, true);
  288.  
  289. })(Promise);