4chan WebM Auto-Resume

Resumes playback of paused WebM videos when scrolled into view

As of 25/07/2018. See the latest version.

  1. // ==UserScript==
  2. // @name 4chan WebM Auto-Resume
  3. // @description Resumes playback of paused WebM videos when scrolled into view
  4. // @namespace https://github.com/marktaiwan/
  5. // @homepageURL https://github.com/marktaiwan/4chan-Webm-Auto-Resume
  6. // @supportURL https://github.com/marktaiwan/4chan-Webm-Auto-Resume/issues
  7. // @license MIT
  8. // @version 0.1
  9. // @author Marker
  10. // @include *//boards.4chan.org/*
  11. // @grant none
  12. // @noframe
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let ticking = false;
  18.  
  19. function isVisible(ele) {
  20. const {top, bottom} = ele.getBoundingClientRect();
  21. return (top > 0 || bottom > 0) && (top < document.documentElement.clientHeight);
  22. }
  23.  
  24. function pausedByUser(video) {
  25. return (video.dataset.userPauseState === '1');
  26. }
  27.  
  28. function pauseHandler(event) {
  29. const video = event.target;
  30. // Video is still in view when paused, therefore it's triggered by the user
  31. if (isVisible(video)) video.dataset.userPauseState = '1';
  32. }
  33.  
  34. function playHandler(event) {
  35. const video = event.target;
  36. if (pausedByUser(video)) video.dataset.userPauseState = '0';
  37. }
  38.  
  39. function initVideoElement(video) {
  40. if (video.dataset.userPauseState === undefined) {
  41. video.dataset.userPauseState = '0';
  42. video.addEventListener('pause', pauseHandler);
  43. video.addEventListener('play', playHandler);
  44. }
  45. }
  46.  
  47. document.addEventListener('scroll', () => {
  48. if (!ticking) {
  49. window.requestAnimationFrame(() => {
  50.  
  51. const expandedVideos = document.querySelectorAll('.expandedWebm');
  52. for (const video of expandedVideos) {
  53. initVideoElement(video);
  54. if (video.paused && isVisible(video) && !pausedByUser(video)) {
  55. video.play();
  56. }
  57. }
  58. ticking = false;
  59.  
  60. });
  61. ticking = true;
  62. }
  63. });
  64. })();