Resize YT To Window Size

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

当前为 2014-05-14 提交的版本,查看 最新版本

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