Resize YT To Window Size

Moves the video to the top of the website and resizes it to the screen size.

当前为 2014-08-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Resize YT To Window Size
  3. // @description Moves the video to the top of the website and resizes it to the screen size.
  4. // @author Chris H (Zren / Shade)
  5. // @icon http://youtube.com/favicon.ico
  6. // @homepageURL https://github.com/Zren/ResizeYoutubePlayerToWindowSize/
  7. // @namespace http://xshade.ca
  8. // @version 1.40
  9. // @include http*://*.youtube.com/*
  10. // @include http*://youtube.com/*
  11. // @include http*://*.youtu.be/*
  12. // @include http*://youtu.be/*
  13. // ==/UserScript==
  14.  
  15. // Github: https://github.com/Zren/ResizeYoutubePlayerToWindowSize
  16. // GreasyFork: https://greasyfork.org/scripts/811-resize-yt-to-window-size
  17. // OpenUserJS.org: https://openuserjs.org/scripts/zren/httpxshade.ca/Resize_YT_To_Window_Size
  18. // Userscripts.org: http://userscripts.org:8080/scripts/show/153699
  19.  
  20. (function (window) {
  21. "use strict";
  22.  
  23. //--- Imported Globals
  24. var yt = window.yt;
  25.  
  26. //--- Utils
  27. function isStringType(obj) { return typeof obj === 'string'; }
  28. function isArrayType(obj) { return obj instanceof Array; }
  29. function isObjectType(obj) { return typeof obj === 'object'; }
  30. function isUndefined(obj) { return typeof obj === 'undefined'; }
  31. function buildVenderPropertyDict(propertyNames, value) {
  32. var d = {};
  33. for (var i in propertyNames)
  34. d[propertyNames[i]] = value;
  35. return d;
  36. }
  37.  
  38. //--- jQuery
  39. // Based on jQuery
  40. // https://github.com/jquery/jquery/blob/master/src/manipulation.js
  41. var core_rnotwhite = /\S+/g;
  42. var rclass = /[\t\r\n\f]/g;
  43. var rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
  44.  
  45. var jQuery = {
  46. trim: function( text ) {
  47. return (text || "").replace( rtrim, "" );
  48. },
  49. addClass: function( elem, value ) {
  50. var classes, cur, clazz, j,
  51. proceed = typeof value === "string" && value;
  52.  
  53. if ( proceed ) {
  54. // The disjunction here is for better compressibility (see removeClass)
  55. classes = ( value || "" ).match( core_rnotwhite ) || [];
  56.  
  57. cur = elem.nodeType === 1 && ( elem.className ?
  58. ( " " + elem.className + " " ).replace( rclass, " " ) :
  59. " "
  60. );
  61.  
  62. if ( cur ) {
  63. j = 0;
  64. while ( (clazz = classes[j++]) ) {
  65. if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
  66. cur += clazz + " ";
  67. }
  68. }
  69. elem.className = jQuery.trim( cur );
  70. }
  71. }
  72. },
  73. removeClass: function( elem, value ) {
  74. var classes, cur, clazz, j,
  75. proceed = arguments.length === 0 || typeof value === "string" && value;
  76.  
  77. if ( proceed ) {
  78. classes = ( value || "" ).match( core_rnotwhite ) || [];
  79.  
  80. // This expression is here for better compressibility (see addClass)
  81. cur = elem.nodeType === 1 && ( elem.className ?
  82. ( " " + elem.className + " " ).replace( rclass, " " ) :
  83. ""
  84. );
  85.  
  86. if ( cur ) {
  87. j = 0;
  88. while ( (clazz = classes[j++]) ) {
  89. // Remove *all* instances
  90. while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
  91. cur = cur.replace( " " + clazz + " ", " " );
  92. }
  93. }
  94. elem.className = value ? jQuery.trim( cur ) : "";
  95. }
  96. }
  97. }
  98. };
  99.  
  100.  
  101. //--- Stylesheet
  102. var JSStyleSheet = function(id) {
  103. this.id = id;
  104. this.stylesheet = '';
  105. };
  106.  
  107. JSStyleSheet.prototype.buildRule = function(selector, styles) {
  108. var s = "";
  109. for (var key in styles) {
  110. s += "\t" + key + ": " + styles[key] + ";\n";
  111. }
  112. return selector + " {\n" + s + "}\n";
  113. };
  114.  
  115. JSStyleSheet.prototype.appendRule = function(selector, k, v) {
  116. if (isArrayType(selector))
  117. selector = selector.join(',\n');
  118. var newStyle;
  119. if (!isUndefined(k) && !isUndefined(v) && isStringType(k)) { // v can be any type (as we stringify it).
  120. // appendRule('#blarg', 'display', 'none');
  121. var d = {};
  122. d[k] = v;
  123. newStyle = this.buildRule(selector, d);
  124. } else if (!isUndefined(k) && isUndefined(v) && isObjectType(k)) {
  125. // appendRule('#blarg', {'display': 'none'});
  126. newStyle = this.buildRule(selector, k);
  127. } else {
  128. // Invalid Arguments
  129. console.log('Illegal arguments', arguments);
  130. return;
  131. }
  132.  
  133. this.stylesheet += newStyle;
  134. };
  135.  
  136. JSStyleSheet.injectIntoHeader = function(injectedStyleId, stylesheet) {
  137. var styleElement = document.getElementById(injectedStyleId);
  138. if (!styleElement) {
  139. styleElement = document.createElement('style');
  140. styleElement.type = 'text/css';
  141. styleElement.id = injectedStyleId;
  142. document.getElementsByTagName('head')[0].appendChild(styleElement);
  143. }
  144. styleElement.appendChild(document.createTextNode(stylesheet));
  145. };
  146.  
  147. JSStyleSheet.prototype.injectIntoHeader = function(injectedStyleId, stylesheet) {
  148. JSStyleSheet.injectIntoHeader(this.id, this.stylesheet);
  149. };
  150.  
  151. //--- Constants
  152. var scriptShortName = 'ytwp'; // YT Window Player
  153. var scriptStyleId = scriptShortName + '-style'; // ytwp-style
  154. var scriptBodyClassId = scriptShortName + '-window-player'; // .ytwp-window-player
  155. var viewingVideoClassId = scriptShortName + '-viewing-video'; // .ytwp-viewing-video
  156. var topOfPageClassId = scriptShortName + '-scrolltop'; // .ytwp-scrolltop
  157. var scriptBodyClassSelector = 'body.' + scriptBodyClassId; // body.ytwp-window-player
  158.  
  159. var videoContainerId = 'player';
  160. var videoContainerPlacemarkerId = scriptShortName + '-placemarker'; // ytwp-placemarker
  161.  
  162. var transitionProperties = ["transition", "-ms-transition", "-moz-transition", "-webkit-transition", "-o-transition"];
  163.  
  164. //--- YTWP
  165. var ytwp = window.ytwp = {
  166. scriptShortName: scriptShortName, // YT Window Player
  167. log_: function(logger, args) { logger.apply(console, ['[' + this.scriptShortName + '] '].concat(Array.prototype.slice.call(args))); return 1; },
  168. log: function() { return this.log_(console.log, arguments); },
  169. error: function() { return this.log_(console.error, arguments); },
  170.  
  171. initialized: false,
  172. pageReady: false,
  173. watchPage: false,
  174. html5PlayerSeekFixAttemptCount: 0,
  175. };
  176.  
  177. ytwp.util = {
  178. isWatchUrl: function (url) {
  179. if (!url)
  180. url = window.location.href;
  181. return url.match(/https?:\/\/(www\.)?youtube.com\/watch\?/);
  182. }
  183. };
  184.  
  185. ytwp.event = {
  186. init: function() {
  187. ytwp.log('init');
  188. if (ytwp.initialized) return;
  189.  
  190. ytwp.isWatchPage = ytwp.util.isWatchUrl();
  191. if (!ytwp.isWatchPage) return;
  192.  
  193. ytwp.event.initStyle();
  194. ytwp.event.initScroller();
  195. ytwp.initialized = true;
  196. ytwp.pageReady = false;
  197. ytwp.html5PlayerSeekFixAttemptCount = 0;
  198. ytwp.html5PlayerSeekFixMaxAttempts = 20;
  199. },
  200. initScroller: function() {
  201. // Register listener & Call it now.
  202. unsafeWindow.addEventListener('scroll', ytwp.event.onScroll, false);
  203. unsafeWindow.addEventListener('resize', ytwp.event.onScroll, false);
  204. ytwp.event.onScroll();
  205. },
  206. onScroll: function() {
  207. var viewportHeight = document.documentElement.clientHeight;
  208.  
  209. // topOfPageClassId
  210. if (unsafeWindow.scrollY == 0) {
  211. jQuery.addClass(document.body, topOfPageClassId);
  212. } else {
  213. jQuery.removeClass(document.body, topOfPageClassId);
  214. }
  215.  
  216. // viewingVideoClassId
  217. if (unsafeWindow.scrollY <= viewportHeight) {
  218. jQuery.addClass(document.body, viewingVideoClassId);
  219. } else {
  220. jQuery.removeClass(document.body, viewingVideoClassId);
  221. }
  222. },
  223. initStyle: function() {
  224. ytwp.log('initStyle');
  225. ytwp.style = new JSStyleSheet(scriptStyleId);
  226. ytwp.event.buildStylesheet();
  227. ytwp.style.injectIntoHeader();
  228. },
  229. buildStylesheet: function() {
  230. ytwp.log('buildStylesheet');
  231. //--- Video Player
  232.  
  233. //
  234. var d;
  235. d = buildVenderPropertyDict(transitionProperties, 'left 0s linear, padding-left 0s linear');
  236. d['padding'] = '0 !important';
  237. d['margin'] = '0 !important';
  238. ytwp.style.appendRule([
  239. scriptBodyClassSelector + ' #player',
  240. scriptBodyClassSelector + '.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible #player',
  241. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player',
  242. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player-legacy',
  243. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #watch7-main-container',
  244. ], d);
  245. //
  246. d = buildVenderPropertyDict(transitionProperties, 'width 0s linear, left 0s linear');
  247.  
  248. // Bugfix for Firefox
  249. // Parts of the header (search box) are hidden under the player.
  250. // Firefox doesn't seem to be using the fixed header+guide yet.
  251. d['float'] = 'initial';
  252.  
  253. ytwp.style.appendRule(scriptBodyClassSelector + ' #player-api', d);
  254.  
  255. // !important is mainly for simplicity, but is needed to override the !important styling when the Guide is open due to:
  256. // .sidebar-collapsed #watch7-video, .sidebar-collapsed #watch7-main, .sidebar-collapsed .watch7-playlist { width: 945px!important; }
  257. // Also, Youtube Center resizes #player at element level.
  258. ytwp.style.appendRule(
  259. [
  260. scriptBodyClassSelector + ' #player',
  261. scriptBodyClassSelector + ' #movie_player',
  262. scriptBodyClassSelector + ' #player-mole-container',
  263. scriptBodyClassSelector + ' .html5-video-content',
  264. scriptBodyClassSelector + ' .html5-main-video',
  265. ],
  266. {
  267. 'width': '100% !important',
  268. 'min-width': '100% !important',
  269. 'max-width': '100% !important',
  270. 'height': '100% !important',
  271. 'min-height': '100% !important',
  272. 'max-height': '100% !important',
  273. }
  274. );
  275. // ytwp.style.appendRule(
  276. // [
  277. // scriptBodyClassSelector + ' .html5-progress-bar',
  278. // ],
  279. // {
  280. // 'width': '100% !important',
  281. // 'min-width': '100% !important',
  282. // 'max-width': '100% !important',
  283. // }
  284. // );
  285.  
  286.  
  287. // Resize #player-unavailable, #player-api
  288. // Using min/max width/height will keep
  289. ytwp.style.appendRule(scriptBodyClassSelector + ' #player .player-width', 'width', '100% !important');
  290. ytwp.style.appendRule(scriptBodyClassSelector + ' #player .player-height', 'height', '100% !important');
  291.  
  292.  
  293. //--- Sidebar
  294.  
  295. // Remove the transition delay as you can see it moving on page load.
  296. d = buildVenderPropertyDict(transitionProperties, 'margin-top 0s linear, padding-top 0s linear');
  297. d['margin-top'] = '0 !important';
  298. d['top'] = '0 !important';
  299. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch7-sidebar', d);
  300.  
  301. ytwp.style.appendRule(scriptBodyClassSelector + '.cardified-page #watch7-sidebar-contents', 'padding-top', '0');
  302.  
  303. //--- Absolutely position the fixed header.
  304. // Masthead
  305. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #masthead-positioner', {
  306. 'position': 'absolute',
  307. 'top': '100% !important'
  308. });
  309.  
  310. // Guide
  311. // When watching the video, we need to line it up with the masthead.
  312. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #appbar-guide-menu', {
  313. 'display': 'initial',
  314. 'position': 'absolute',
  315. 'top': '100% !important' // Masthead height
  316. });
  317. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #page.watch #guide', {
  318. 'display': 'initial',
  319. 'margin': '0',
  320. 'position': 'initial'
  321. });
  322.  
  323. //---
  324. // Hide Scrollbars
  325. ytwp.style.appendRule(scriptBodyClassSelector + '.' + topOfPageClassId, 'overflow-x', 'hidden');
  326.  
  327.  
  328. //--- Fix Other Possible Style Issues
  329.  
  330. //--- Whitespace Leftover From Moving The Video
  331. ytwp.style.appendRule(scriptBodyClassSelector + ' #page.watch', 'padding-top', '0');
  332. ytwp.style.appendRule(scriptBodyClassSelector + ' .player-branded-banner', 'height', '0');
  333.  
  334. //--- Playlist Bar
  335. //ytwp.style.appendRule(scriptBodyClassSelector + ' #watch7-playlist-tray-container', "margin", "-15px -10px 20px -10px");
  336. ytwp.style.appendRule(scriptBodyClassSelector + ' .watch7-playlist-bar-left', 'width', '640px !important'); // Same width as .watch-content
  337. ytwp.style.appendRule([
  338. scriptBodyClassSelector + ' .playlist',
  339. scriptBodyClassSelector + ' .playlist .watch7-playlist-bar',
  340. ], 'max-width', '1040px'); // Same width as .watch-content (640px) + .watch-sidebar (300-400px).
  341. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch7-playlist-tray-container', {
  342. "margin-top": "-15px",
  343. "height": "287px !important", // 65 (playlist tile) * 4 + 27 (trim on bottom)
  344. "margin-bottom": "15px"
  345. });
  346. ytwp.style.appendRule([
  347. scriptBodyClassSelector + '.cardified-page #watch7-playlist-tray-container + #watch7-sidebar-contents', // Pre Oct 26
  348. scriptBodyClassSelector + '.cardified-page #watch-appbar-playlist + #watch7-sidebar-contents', // Post Oct 26
  349. ], 'padding-top', '15px');
  350.  
  351. // YT Center
  352. ytwp.style.appendRule(scriptBodyClassSelector + ' #player', 'margin-bottom', '0 !important');
  353. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch7-playlist-tray-container', {
  354. 'left': 'initial !important',
  355. 'width': 'initial !important'
  356. });
  357. ytwp.style.appendRule(scriptBodyClassSelector + ' .watch7-playlist-bar-right', 'width', '363px !important');
  358. },
  359. onWatchInit: function() {
  360. ytwp.log('onWatchInit');
  361. if (!ytwp.initialized) return;
  362. if (ytwp.pageReady) return;
  363.  
  364. ytwp.event.moveVideoContainer();
  365. ytwp.event.movePlaylist();
  366. ytwp.event.addBodyClass();
  367. ytwp.pageReady = true;
  368. },
  369. onWatchDispose: function() {
  370. ytwp.log('onWatchDispose');
  371. if (ytwp.isWatchPage) {
  372. if (ytwp.util.isWatchUrl()) {
  373. ytwp.event.onWatchDisposeToWatch();
  374. } else {
  375. ytwp.event.onWatchDisposeToElsewhere();
  376. }
  377. }
  378. },
  379. onDispose: function() {
  380. ytwp.initialized = false;
  381. ytwp.pageReady = false;
  382. ytwp.isWatchPage = false;
  383. },
  384. onWatchDisposeToWatch: function() {
  385. ytwp.log('onWatchDisposeToWatch');
  386.  
  387. },
  388. onWatchDisposeToElsewhere: function() {
  389. ytwp.log('onWatchDisposeToElsewhere');
  390. // Delete the Video player (as it's not where it normally is).
  391. // var videoContainer = document.getElementById(videoContainerId);
  392. // if (videoContainer)
  393. // videoContainer.remove();
  394. },
  395. moveVideoContainer: function() {
  396. // https://developers.google.com/youtube/js_api_reference#getPlayerState
  397. var PLAYING = 1;
  398. var BUFFERING = 3;
  399. var autoPlay = false;
  400. try {
  401. var playerState = document.getElementById('movie_player').getPlayerState();
  402. autoPlay = playerState == PLAYING || playerState == BUFFERING;
  403. } catch (e) {}
  404.  
  405. ytwp.log('moveVideoContainer');
  406. var videoContainer = document.getElementById(videoContainerId);
  407. var body = document.body;
  408. body.insertBefore(videoContainer, body.firstChild);
  409.  
  410. // Moving the player seems to pause the video for some reason.
  411.  
  412. try {
  413. if (autoPlay) {
  414. document.getElementById('movie_player').playVideo();
  415. ytwp.log('autoplaying');
  416. }
  417. } catch(e) {
  418. // Videos in a playlist will cause this error, but will play fine.
  419. //ytwp.error('Error calling playVideo(). Might not autoplay video.');
  420. }
  421. },
  422. removeVideoContainer: function() {
  423. ytwp.log('removeVideoContainer');
  424. var videoContainer = document.getElementById(videoContainerId);
  425. if (videoContainer)
  426. videoContainer.parentNode.removeChild(videoContainer);
  427. },
  428. movePlaylist: function() {
  429. // --- Old Playlist bar (still in firefox).
  430.  
  431. // Move the bar to the top of the main container.
  432. var mainContainer = document.getElementById('watch7-main-container');
  433. var bar = document.getElementById('playlist');
  434. if (mainContainer && bar) {
  435. mainContainer.insertBefore(bar, mainContainer.firstChild);
  436. ytwp.log('Moved #playlist');
  437. }
  438.  
  439. // Move the tray to inside the sidebar
  440. var tray = document.getElementById('watch7-playlist-tray-container');
  441. var sidebar = document.getElementById('watch7-sidebar');
  442. if (tray && sidebar) {
  443. sidebar.insertBefore(tray, sidebar.firstChild);
  444. ytwp.log('Moved #watch7-playlist-tray-container');
  445. }
  446. },
  447. addBodyClass: function() {
  448. // Insert CSS Into the body so people can style around the effects of this script.
  449. jQuery.addClass(document.body, scriptBodyClassId);
  450. ytwp.log('Applied ' + scriptBodyClassSelector);
  451. },
  452. html5PlayerSeekFix: function() {
  453. var videoContainer = document.getElementById(videoContainerId);
  454. if (videoContainer) {
  455. if (ytwp.html5PlayerSeekFixAttemptCount < ytwp.html5PlayerSeekFixMaxAttempts) {
  456. var playerWidth = document.querySelector('#player').offsetWidth;
  457. var progressBarWidth = document.querySelector('.html5-progress-bar').offsetWidth;
  458. console.log(playerWidth, progressBarWidth)
  459. if (playerWidth != progressBarWidth) {
  460. document.documentElement.setAttribute('data-player-size', '');
  461. var watchClasses = [
  462. 'watch-small',
  463. 'watch-medium',
  464. 'watch-medium-540',
  465. 'watch-large'
  466. ];
  467. for (var i = watchClasses.length - 1; i >= 0; i--) {
  468. jQuery.removeClass(videoContainer, watchClasses[i]);
  469. }
  470.  
  471. // Trigger a refresh of the player sizes.
  472. document.querySelector('.ytp-size-toggle-small, .ytp-size-toggle-large').click();
  473. ytwp.log('html5PlayerSeekFix', ++ytwp.html5PlayerSeekFixAttemptCount);
  474. }
  475. }
  476. }
  477. }
  478. };
  479.  
  480.  
  481. ytwp.pubsubListeners = {
  482. 'init': function() { // Not always called
  483. ytwp.event.init();
  484. ytwp.event.onWatchInit();
  485. },
  486. 'init-watch': function() { // Not always called
  487. ytwp.event.init();
  488. ytwp.event.onWatchInit();
  489. },
  490. 'player-added': function() { // Not always called
  491. // Usually called after init-watch, however this is called before init when going from channel -> watch page.
  492. // The init event is when the body element resets all it's classes.
  493. ytwp.event.init();
  494. ytwp.event.onWatchInit();
  495. },
  496. 'player-resize': function() {
  497. ytwp.event.html5PlayerSeekFix();
  498. },
  499. 'player-playback-start': function() {
  500. ytwp.event.html5PlayerSeekFix();
  501. },
  502. 'appbar-guide-delay-load': function() {
  503. // Listen to a later event that is always called in case the others are missed.
  504. ytwp.event.init();
  505. ytwp.event.onWatchInit();
  506.  
  507. // Channel -> /watch
  508. if (ytwp.util.isWatchUrl())
  509. ytwp.event.addBodyClass();
  510.  
  511. ytwp.event.html5PlayerSeekFix();
  512. },
  513. 'yt-www-pageFrameCssNotifications-load': function() {
  514. ytwp.event.html5PlayerSeekFix();
  515. },
  516. 'dispose-watch': function() {
  517. ytwp.event.onWatchDispose();
  518. },
  519. 'dispose': function() {
  520. ytwp.event.onDispose();
  521. }
  522. };
  523.  
  524. ytwp.initLogging = function() {
  525.  
  526. };
  527.  
  528. ytwp.registerYoutubeListeners = function() {
  529. // ytwp.registerYoutubePlayerApiListeners();
  530. ytwp.registerYoutubePubSubListeners();
  531. };
  532.  
  533. ytwp.registerYoutubePlayerApiListeners = function() {
  534. var onYouTubePlayerReady_old = onYouTubePlayerReady;
  535. onYouTubePlayerReady = function() {
  536. onYouTubePlayerReady_old.apply(this, arguments);
  537. };
  538. };
  539.  
  540. ytwp.registerYoutubePubSubListeners = function() {
  541. // Debugging Youtubes Events
  542. // var yt_pubsub_publish = yt.pubsub.instance_.publish;
  543. // yt.pubsub.instance_.publish = function(){
  544. // // ytwp.log(arguments);
  545. // ytwp.log('[pubsub]', arguments[0]);
  546. // yt_pubsub_publish.apply(this, arguments);
  547. // };
  548.  
  549. // Subscribe
  550. for (var eventName in ytwp.pubsubListeners) {
  551. var eventListener = ytwp.pubsubListeners[eventName];
  552. yt.pubsub.instance_.subscribe(eventName, eventListener);
  553. }
  554. };
  555.  
  556. ytwp.main = function() {
  557. ytwp.initLogging();
  558. try {
  559. ytwp.registerYoutubeListeners();
  560. } catch(e) {
  561. ytwp.error("Could not hook yt.pubsub");
  562. }
  563. };
  564.  
  565. ytwp.main();
  566. })(unsafeWindow);