YouTube Click To Play

它禁用自动播放,并启用点击播放。

  1. // ==UserScript==
  2. // @name YouTube Click To Play
  3. // @name:ja YouTube Click To Play
  4. // @name:zh-CN YouTube Click To Play
  5. // @namespace knoa.jp
  6. // @description It disables autoplay and enables click to play.
  7. // @description:ja 自動再生を無効にし、クリックで再生するようにします。
  8. // @description:zh-CN 它禁用自动播放,并启用点击播放。
  9. // @include https://www.youtube.com/*
  10. // @noframes
  11. // @run-at document-start
  12. // @grant none
  13. // @version 1.1.7
  14. // ==/UserScript==
  15.  
  16. (function(){
  17. const SCRIPTID = 'YouTubeClickToPlay';
  18. const SCRIPTNAME = 'YouTube Click To Play';
  19. const DEBUG = false;/*
  20. [update] 1.1.7
  21. sorry, fixed a cheap bug.
  22.  
  23. [bug]
  24.  
  25. [todo]
  26.  
  27. [possible]
  28. t=n 指定があればむしろサムネではなくその時点の映像にしてあげる?
  29. 0秒で常にサムネに戻る仕様?(seekingイベントでよい)
  30. channel/ と watch/ は個別に設定可能とか
  31. => channelだけで動作する別スクリプトがある
  32. document.hidden でのみ作動するオプションとか
  33.  
  34. [research]
  35. シアターモードの切り替えで再生してしまう件(そこまで気にしなくてもいい気もする)
  36.  
  37. [memo]
  38. 本スクリプト仕様:
  39. サムネになってほしい: チャンネルホーム, ビデオページ
  40. 再生してほしい: LIVE, 広告, 途中広告からの復帰
  41. 要確認: 各ページの行き来, 再生で即停止しないこと, シアターモードの切り替え, 背面タブでの起動
  42. (YouTubeによるあっぱれなユーザー体験の追究のおかげで、初回読み込み時に限り再生開始済みのvideo要素が即出現する)
  43. YouTube仕様:
  44. 画面更新(URL Enter, S-Reload, Reload に本質的な差異なし)
  45. 新規タブ(開いた直後, 読み込み完了後, title変更後 に本質的な差異なし)
  46. video: body ... video ... loadstart ... で必ず play() されるのでダミーと入れ替えておけばよい。
  47. video要素は #player-api 内に出現した後に ytd-watch-flexy 内に移動する。その際に play() されるようだ。
  48. t=123 のような時刻指定があると seeking 後にもう一度 play() される。
  49. thumbnail は t=4 以下だとなぜか消えてしまう。(seekじゃなくてadvanceだとみなされるせい?)
  50. channel: body ... video ... loadstart で即 pause() 可能。(playは踏まれない)
  51. 画面遷移(動画 <=> LIVE <=> チャンネル)
  52. video: yt-navigate-start ... loadstart で即 pause() 可能。(playは踏まれない)
  53. 広告
  54. 冒頭広告: .ad-showing 依存だが判定できる。
  55. 広告明け: 少しだけ泥臭いが、そのURLで一度でも本編が再生されていれば広告明けとみなす。
  56. 広告が入ると広告のサムネイルがセットされた状態になるので、独自にセットしなければならない。
  57. Firefoxなどのブラウザが動画の自動再生をくい止めた場合に備えて広告のサムネイルになると推測。
  58. 参考:
  59. Channelトップの動画でのみ機能するスクリプト
  60. https://gf.qytechs.cn/ja/scripts/399862-kill-youtube-channel-video-autoplay
  61. */
  62. if(window === top && console.time) console.time(SCRIPTID);
  63. const MS = 1, SECOND = 1000*MS, MINUTE = 60*SECOND, HOUR = 60*MINUTE, DAY = 24*HOUR, WEEK = 7*DAY, MONTH = 30*DAY, YEAR = 365*DAY;
  64. const THUMBNAILURL = 'https://i.ytimg.com/vi/{id}/maxresdefault.jpg';
  65. const SDTHUMBNAILURL = 'https://i.ytimg.com/vi/{id}/sddefault.jpg';
  66. const HQTHUMBNAILURL = 'https://i.ytimg.com/vi/{id}/hqdefault.jpg';
  67. const FLAGNAME = SCRIPTID.toLowerCase();
  68. const site = {
  69. get: {
  70. moviePlayer: () => $('#movie_player'),
  71. spinner: () => $('.ytp-spinner'),
  72. video: () => $(`video:not([data-${FLAGNAME}])`),
  73. videoId: (url) => (new URL(url)).searchParams.get('v'),
  74. startTime: () => {
  75. /* t=1h0m0s or t=3600 */
  76. let t = (new URL(location.href)).searchParams.get('t');
  77. if(t === null) return;
  78. let [h, m, s] = t.match(/^(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s?)?$/).slice(1).map(n => parseInt(n || 0));
  79. return 60*60*h + 60*m + s;
  80. },
  81. },
  82. is: {
  83. immediate: (video) => $('#player-api', player => player.contains(video)),
  84. live: () => $('.ytp-time-display.ytp-live') !== null,
  85. ad: () => $('#movie_player.ad-showing') !== null,
  86. list: () => (new URL(location)).searchParams.get('list') !== null,
  87. autoplay: () => $('ytd-watch-next-secondary-results-renderer paper-toggle-button.ytd-compact-autoplay-renderer', button => button.checked),
  88. },
  89. views: {
  90. channel: {
  91. url: /^https:\/\/www\.youtube\.com\/(channel|c|user)\//,
  92. get: {
  93. thumbnailOverlayImage: () => $('.ytp-cued-thumbnail-overlay-image'),
  94. thumbnailURL: () => THUMBNAILURL.replace('{id}', view.get.videoId()),
  95. sdThumbnailURL: () => SDTHUMBNAILURL.replace('{id}', view.get.videoId()),
  96. videoId: () => $('a.ytp-title-link[href]', a => site.get.videoId(a.href)),
  97. },
  98. },
  99. watch: {
  100. url: /^https:\/\/www\.youtube\.com\/watch\?/,
  101. get: {
  102. thumbnailOverlayImage: () => $('.ytp-cued-thumbnail-overlay-image'),
  103. thumbnailURL: () => THUMBNAILURL.replace('{id}', view.get.videoId()),
  104. sdThumbnailURL: () => SDTHUMBNAILURL.replace('{id}', view.get.videoId()),
  105. hqThumbnailURL: () => HQTHUMBNAILURL.replace('{id}', view.get.videoId()),
  106. videoId: () => site.get.videoId(location.href),
  107. upnextId: () => $('ytd-compact-autoplay-renderer a[href]', a => site.get.videoId(a.href)),
  108. playlistAutoplayInsertBefore: () => $('ytd-watch-flexy #playlist-actions #save-button'),
  109. autoplayLabel: () => $('#upnext + #autoplay'),
  110. },
  111. },
  112. },
  113. };
  114. let elements = {}, flags = {}, view;
  115. const core = {
  116. initialize: function(){
  117. elements.html = document.documentElement;
  118. elements.html.classList.add(SCRIPTID);
  119. core.findVideo();
  120. core.addStyle('style');
  121. },
  122. findVideo: function(){
  123. const found = function(video){
  124. //log(video);
  125. if(video.dataset[FLAGNAME]) return;
  126. video.dataset[FLAGNAME] = 'found';
  127. core.listenNavigation();
  128. core.listenVideo(video);
  129. };
  130. /* if a video already exists */
  131. let video = site.get.video();
  132. if(video) found(video);
  133. /* unavoidably observate body for immediate catch */
  134. observe(document.documentElement, function(records){
  135. let video = site.get.video();
  136. if(video) found(video);
  137. }, {childList: true, subtree: true});
  138. },
  139. listenNavigation: function(){
  140. /* listen navigation (observe URL changes) */
  141. if(flags.listeningNavigation !== undefined) return;
  142. flags.listeningNavigation = true;
  143. let listener = function(e){
  144. //log(e.type, location.href);
  145. delete flags.upnextId;/* reset the upnext video id */
  146. delete flags.shownAd;/* reset the shown ad status */
  147. delete flags.playedOnce;/* reset the played once status */
  148. view = core.getView(site.views);
  149. if(view && view.key === 'watch'){
  150. flags.upnextId = view.get.upnextId();
  151. if(site.is.list()) core.setPlaylistAutoplay();
  152. else core.getAutoplayLabel();
  153. }
  154. };
  155. document.addEventListener('yt-navigate-start', listener);/* click a link */
  156. window.addEventListener('popstate', listener);/* browser back or foward */
  157. listener({type: 'theVeryFirst'});/* at the very first */
  158. },
  159. listenVideo: function(video){
  160. let shouldStop = function(video){
  161. if(site.is.live()) return log('this is a live and should not stop playing');
  162. if(site.is.ad()) return flags.shownAd = true, log('this is an ad and should not stop playing.');/* shown ad on the current location */
  163. if(site.is.list() && flags.autoplayOnPlaylist) return log('this is on the playlist and should not stop playing.');
  164. if(site.is.autoplay() && flags.upnextId === view.get.videoId()) return log('site is set to autoplay and should not stop playing.');
  165. if(flags.playedOnce) return log('the ad has just closed and the video should continue playing.');
  166. return true;
  167. };
  168. /* for the very immediate time */
  169. //log(video.currentSrc, 'paused:' + video.paused, 'currentTime:' + video.currentTime);
  170. if(shouldStop()){
  171. core.stopAutoplay(video);
  172. core.stopImmediateAutoplay(video);
  173. }
  174. /* the video element just changes its src attribute on any case */
  175. video.addEventListener('loadstart', function(e){
  176. //log(e.type, video.currentSrc, 'paused:' + video.paused, 'currentTime:' + video.currentTime, flags.shownAd ? 'shownAd' : '', flags.playedOnce ? 'playedOnce' : '');
  177. if(shouldStop()){
  178. core.stopAutoplay(video);
  179. /* ads just finished and the video is starting */
  180. if(!site.is.ad() && flags.shownAd && !flags.playedOnce) video.addEventListener('canplay', function(e){
  181. //log(e.type);
  182. core.imitateUnstarted(video);
  183. }, {once: true});
  184. }
  185. });
  186. /* memorize played status for restarting playing or not on after ads */
  187. video.addEventListener('playing', function(e){
  188. //log(e.type, 'currentTime:' + video.currentTime);
  189. if(!site.is.ad() && !flags.playedOnce) return flags.playedOnce = true;/* played once on the current location */
  190. });
  191. },
  192. stopAutoplay: function(video){
  193. //log();
  194. video.autoplay = false;
  195. video.pause();
  196. },
  197. stopImmediateAutoplay: function(video){
  198. let count = 0, isImmediate = site.is.immediate(video), startTime = site.get.startTime();
  199. //log('isImmediate:' + isImmediate, 'startTime:' + startTime, 'currentTime:' + video.currentTime);
  200. if(isImmediate) count++;/* for the very first view of the YouTube which plays a video automatically for immediate user experience */
  201. if(startTime) count++;/* for starting again from middle after seeking with query like t=123 */
  202. if(count){
  203. video.originalPlay = video.play;
  204. video.play = function(){
  205. //log('(play)', 'count:' + count, site.is.ad() ? 'ad' : '', 'currentTime:' + video.currentTime);
  206. if(site.is.ad()) return video.originalPlay();
  207. if(--count === 0) video.play = video.originalPlay;
  208. let spinner = site.get.spinner();
  209. if(spinner) spinner.style.display = 'none';
  210. };
  211. }
  212. /* I don't know why but on t < 5, it'll surely be paused but player UI is remained playing. So... */
  213. if(startTime && startTime < 5) video.addEventListener('seeked', function(e){
  214. //log(e.type, 'currentTime:' + video.currentTime);
  215. if(flags.shownAd) return;/*will imitate by canplay event listener*/
  216. core.imitateUnstarted(video);
  217. }, {once: true});
  218. },
  219. imitateUnstarted: function(video){
  220. //log();
  221. let player = site.get.moviePlayer();
  222. core.setThumbnail(video);
  223. player.classList.add('imitated-unstarted-mode');
  224. video.addEventListener('play', function(e){
  225. //log(e.type, 'now imitated-unstarted-mode', player.classList.contains('imitated-unstarted-mode'));
  226. video.addEventListener('play', function(e){
  227. //log(e.type, 'removing imitated-unstarted-mode', player.classList.contains('imitated-unstarted-mode'));
  228. player.classList.remove('imitated-unstarted-mode');
  229. }, {once: true});
  230. }, {once: true});
  231. video.play();
  232. video.pause();
  233. },
  234. setThumbnail: function(video){
  235. //log();
  236. /* normally it will automatically be set, but it won't after ads */
  237. if(view === undefined) return;
  238. core.getTarget(view.get.thumbnailOverlayImage).then(thumbnail => {
  239. /* set the thumbnail of maxres */
  240. let thumbnailURL = view.get.thumbnailURL();
  241. thumbnail.style.backgroundImage = `url(${thumbnailURL})`;
  242. /* if it doesn't have maxres... */
  243. let makePromise = function(url){
  244. return new Promise(function(resolve, reject){
  245. let img = new Image();
  246. img.src = url;
  247. img.addEventListener('load', e => resolve(img));
  248. img.addEventListener('error', e => reject(img));
  249. });
  250. };
  251. Promise.all([
  252. makePromise(thumbnailURL),
  253. makePromise(view.get.sdThumbnailURL()),
  254. makePromise(view.get.hqThumbnailURL()),
  255. ]).then((imgs) => {
  256. //log(imgs);
  257. imgs.sort((a, b) => b.naturalWidth - a.naturalWidth);
  258. if(thumbnailURL === imgs[0].src) return;
  259. thumbnail.style.backgroundImage = `url(${imgs[0].src})`;
  260. });
  261. });
  262. },
  263. setPlaylistAutoplay: function(){
  264. //log();
  265. if(flags.autoplayOnPlaylist !== undefined) return;
  266. flags.autoplayOnPlaylist = Storage.read('autoplayOnPlaylist');
  267. core.getTarget(view.get.playlistAutoplayInsertBefore).then(insertBefore => {
  268. let autoplaySwitch = createElement(html.autoplaySwitch(flags.autoplayLabel || Storage.read('autoplayLabel'))), button = autoplaySwitch.querySelector('paper-toggle-button');
  269. if(flags.autoplayOnPlaylist) button.checked = true;
  270. /* YouTube listens tap event for toggling playlist collapse */
  271. autoplaySwitch.addEventListener('tap', function(e){
  272. //log(e, button, button.checked ? 'checked' : '');
  273. if(button.checked) flags.autoplayOnPlaylist = true;
  274. else flags.autoplayOnPlaylist = false;
  275. Storage.save('autoplayOnPlaylist', flags.autoplayOnPlaylist);
  276. e.stopPropagation();
  277. });
  278. insertBefore.parentNode.insertBefore(autoplaySwitch, insertBefore);
  279. });
  280. },
  281. getAutoplayLabel: function(){
  282. //log();
  283. /* get the label everytime for catching language change, it's not such a heavy task' */
  284. core.getTarget(view.get.autoplayLabel).then(autoplayLabel => {
  285. if(autoplayLabel.textContent === flags.autoplayLabel) return;
  286. flags.autoplayLabel = autoplayLabel.textContent;
  287. Storage.save('autoplayLabel', flags.autoplayLabel);
  288. });
  289. },
  290. getView: function(views){
  291. Object.keys(views).forEach(key => views[key].key = key);
  292. let key = Object.keys(views).find(key => views[key].url.test(location.href));
  293. if(key === undefined) return log('Doesn\'t match any views:', location.href);
  294. else return views[key];
  295. },
  296. getTarget: function(selector, retry = 10, interval = 1*SECOND){
  297. const key = selector.name;
  298. const get = function(resolve, reject){
  299. let selected = selector();
  300. if(selected && selected.length > 0) selected.forEach((s) => s.dataset.selector = key);/* elements */
  301. else if(selected instanceof HTMLElement) selected.dataset.selector = key;/* element */
  302. else if(--retry) return log(`Not found: ${key}, retrying... (${retry})`), setTimeout(get, interval, resolve, reject);
  303. else return reject(new Error(`Not found: ${selector.name}, I give up.`));
  304. elements[key] = selected;
  305. resolve(selected);
  306. };
  307. return new Promise(function(resolve, reject){
  308. get(resolve, reject);
  309. });
  310. },
  311. getTargets: function(selectors, retry = 10, interval = 1*SECOND){
  312. return Promise.all(Object.values(selectors).map(selector => core.getTarget(selector, retry, interval)));
  313. },
  314. addStyle: function(name = 'style'){
  315. if(html[name] === undefined) return;
  316. let style = createElement(html[name]());
  317. document.head.appendChild(style);
  318. if(elements[name] && elements[name].isConnected) document.head.removeChild(elements[name]);
  319. elements[name] = style;
  320. },
  321. };
  322. const html = {
  323. /* YouTube itself will append the button structure to paper-toggle-button, it's so fragile!! */
  324. autoplaySwitch: (label = 'AUTOPLAY') => `
  325. <div id="head" class="style-scope ytd-compact-autoplay-renderer" data-${FLAGNAME}="playlist-autoplay">
  326. <div id="autoplay" class="style-scope ytd-compact-autoplay-renderer">${label}</div>
  327. <paper-toggle-button id="toggle" noink="" class="style-scope ytd-compact-autoplay-renderer" role="button" aria-pressed="false" tabindex="0" toggles="" aria-disabled="false" aria-label="${label}" style="touch-action: pan-y;"></paper-toggle-button>
  328. </div>
  329. `,
  330. style: () => `
  331. <style type="text/css" id="${SCRIPTID}-style">
  332. /* less bold gradient */
  333. #movie_player .ytp-gradient-bottom{
  334. background: linear-gradient(to top,
  335. rgba(0,0,0,.64) 0px,
  336. rgba(0,0,0,.49) 15px,
  337. rgba(0,0,0,.36) 30px,
  338. rgba(0,0,0,.25) 45px,
  339. rgba(0,0,0,.16) 60px,
  340. rgba(0,0,0,.09) 75px,
  341. rgba(0,0,0,.04) 90px,
  342. rgba(0,0,0,.01) 105px,
  343. rgba(0,0,0,.00) 120px,
  344. transparent
  345. ) !important;/*exponential curve*/
  346. opacity: 1;
  347. display: block;
  348. }
  349. /* show thumbnails more clearly; affected only for .unstarted-mode */
  350. #movie_player.unstarted-mode .ytp-gradient-bottom,
  351. #movie_player.imitated-unstarted-mode .ytp-gradient-bottom{
  352. opacity: .5;
  353. }
  354. #movie_player.unstarted-mode:hover .ytp-gradient-bottom,
  355. #movie_player.imitated-unstarted-mode:hover .ytp-gradient-bottom{
  356. opacity: 1;
  357. }
  358. /* prevent from sudden disappearing */
  359. .ytp-autohide .ytp-gradient-bottom{
  360. opacity: 0 !important;
  361. }
  362. /* imitated unstarted mode */
  363. #movie_player.imitated-unstarted-mode .ytp-cued-thumbnail-overlay{
  364. display: block !important;
  365. z-index: 10;
  366. }
  367. /* AUTOPLAY button on the playlist */
  368. [data-${FLAGNAME}="playlist-autoplay"]{
  369. margin-bottom: 0 !important;
  370. }
  371. </style>
  372. `,
  373. };
  374. const setTimeout = window.setTimeout.bind(window), clearTimeout = window.clearTimeout.bind(window), setInterval = window.setInterval.bind(window), clearInterval = window.clearInterval.bind(window), requestAnimationFrame = window.requestAnimationFrame.bind(window);
  375. const alert = window.alert.bind(window), confirm = window.confirm.bind(window), prompt = window.prompt.bind(window), getComputedStyle = window.getComputedStyle.bind(window), fetch = window.fetch.bind(window);
  376. if(!('isConnected' in Node.prototype)) Object.defineProperty(Node.prototype, 'isConnected', {get: function(){return document.contains(this)}});
  377. class Storage{
  378. static key(key){
  379. return (SCRIPTID) ? (SCRIPTID + '-' + key) : key;
  380. }
  381. static save(key, value, expire = null){
  382. key = Storage.key(key);
  383. localStorage[key] = JSON.stringify({
  384. value: value,
  385. saved: Date.now(),
  386. expire: expire,
  387. });
  388. }
  389. static read(key){
  390. key = Storage.key(key);
  391. if(localStorage[key] === undefined) return undefined;
  392. let data = JSON.parse(localStorage[key]);
  393. if(data.value === undefined) return data;
  394. if(data.expire === undefined) return data;
  395. if(data.expire === null) return data.value;
  396. if(data.expire < Date.now()) return localStorage.removeItem(key);/*undefined*/
  397. return data.value;
  398. }
  399. static remove(key){
  400. key = Storage.key(key);
  401. delete localStorage.removeItem(key);
  402. }
  403. static delete(key){
  404. Storage.remove(key);
  405. }
  406. static saved(key){
  407. key = Storage.key(key);
  408. if(localStorage[key] === undefined) return undefined;
  409. let data = JSON.parse(localStorage[key]);
  410. if(data.saved) return data.saved;
  411. else return undefined;
  412. }
  413. }
  414. const $ = function(s, f){
  415. let target = document.querySelector(s);
  416. if(target === null) return null;
  417. return f ? f(target) : target;
  418. };
  419. const $$ = function(s, f){
  420. let targets = document.querySelectorAll(s);
  421. return f ? Array.from(targets).map(t => f(t)) : targets;
  422. };
  423. const createElement = function(html = '<span></span>'){
  424. let outer = document.createElement('div');
  425. outer.innerHTML = html;
  426. return outer.firstElementChild;
  427. };
  428. const observe = function(element, callback, options = {childList: true, characterData: false, subtree: false, attributes: false, attributeFilter: undefined}){
  429. let observer = new MutationObserver(callback.bind(element));
  430. observer.observe(element, options);
  431. return observer;
  432. };
  433. const log = function(){
  434. if(!DEBUG) return;
  435. let l = log.last = log.now || new Date(), n = log.now = new Date();
  436. let error = new Error(), line = log.format.getLine(error), callers = log.format.getCallers(error);
  437. //console.log(error.stack);
  438. console.log(
  439. SCRIPTID + ':',
  440. /* 00:00:00.000 */ n.toLocaleTimeString() + '.' + n.getTime().toString().slice(-3),
  441. /* +0.000s */ '+' + ((n-l)/1000).toFixed(3) + 's',
  442. /* :00 */ ':' + line,
  443. /* caller.caller */ (callers[2] ? callers[2] + '() => ' : '') +
  444. /* caller */ (callers[1] || '') + '()',
  445. ...arguments
  446. );
  447. };
  448. log.formats = [{
  449. name: 'Firefox Scratchpad',
  450. detector: /MARKER@Scratchpad/,
  451. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  452. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  453. }, {
  454. name: 'Firefox Console',
  455. detector: /MARKER@debugger/,
  456. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  457. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  458. }, {
  459. name: 'Firefox Greasemonkey 3',
  460. detector: /\/gm_scripts\//,
  461. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  462. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  463. }, {
  464. name: 'Firefox Greasemonkey 4+',
  465. detector: /MARKER@user-script:/,
  466. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 500,
  467. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  468. }, {
  469. name: 'Firefox Tampermonkey',
  470. detector: /MARKER@moz-extension:/,
  471. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 2,
  472. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  473. }, {
  474. name: 'Chrome Console',
  475. detector: /at MARKER \(<anonymous>/,
  476. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)?$/)[1],
  477. getCallers: (e) => e.stack.match(/[^ ]+(?= \(<anonymous>)/gm),
  478. }, {
  479. name: 'Chrome Tampermonkey',
  480. detector: /at MARKER \(chrome-extension:.*?\/userscript.html\?name=/,
  481. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)?$/)[1] - 1,
  482. getCallers: (e) => e.stack.match(/[^ ]+(?= \(chrome-extension:)/gm),
  483. }, {
  484. name: 'Chrome Extension',
  485. detector: /at MARKER \(chrome-extension:/,
  486. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)?$/)[1],
  487. getCallers: (e) => e.stack.match(/[^ ]+(?= \(chrome-extension:)/gm),
  488. }, {
  489. name: 'Edge Console',
  490. detector: /at MARKER \(eval/,
  491. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1],
  492. getCallers: (e) => e.stack.match(/[^ ]+(?= \(eval)/gm),
  493. }, {
  494. name: 'Edge Tampermonkey',
  495. detector: /at MARKER \(Function/,
  496. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1] - 4,
  497. getCallers: (e) => e.stack.match(/[^ ]+(?= \(Function)/gm),
  498. }, {
  499. name: 'Safari',
  500. detector: /^MARKER$/m,
  501. getLine: (e) => 0,/*e.lineが用意されているが最終呼び出し位置のみ*/
  502. getCallers: (e) => e.stack.split('\n'),
  503. }, {
  504. name: 'Default',
  505. detector: /./,
  506. getLine: (e) => 0,
  507. getCallers: (e) => [],
  508. }];
  509. log.format = log.formats.find(function MARKER(f){
  510. if(!f.detector.test(new Error().stack)) return false;
  511. //console.log('////', f.name, 'wants', 0/*line*/, '\n' + new Error().stack);
  512. return true;
  513. });
  514. core.initialize();
  515. if(window === top && console.timeEnd) console.timeEnd(SCRIPTID);
  516. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址