4chan WebM Auto-Resume

Resumes playback of paused WebM videos when scrolled into view

  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.3
  9. // @author Marker
  10. // @include *//boards.4chan.org/*
  11. // @include *//boards.4channel.org/*
  12. // @grant none
  13. // @noframe
  14. // ==/UserScript==
  15.  
  16. (function () {
  17. 'use strict';
  18. const interval = 100; // millisecond
  19. let lastExecution = Date.now();
  20.  
  21. function isVisible(ele) {
  22. const {top, bottom} = ele.getBoundingClientRect();
  23. return (top > 0 || bottom > 0) && (top < document.documentElement.clientHeight);
  24. }
  25.  
  26. function pausedByUser(video) {
  27. return (video.dataset.userPauseState === '1');
  28. }
  29.  
  30. function pauseHandler(event) {
  31. const video = event.target;
  32.  
  33. // Video is still in view when paused, therefore it's triggered by the user
  34. if (isVisible(video)) video.dataset.userPauseState = '1';
  35. }
  36.  
  37. function playHandler(event) {
  38. const video = event.target;
  39. if (pausedByUser(video)) video.dataset.userPauseState = '0';
  40. }
  41.  
  42. function initVideoElement(video) {
  43. if (video.dataset.userPauseState === undefined) {
  44. video.dataset.userPauseState = '0';
  45. video.addEventListener('pause', pauseHandler);
  46. video.addEventListener('play', playHandler);
  47. }
  48. }
  49.  
  50. document.addEventListener('scroll', () => {
  51. if (Date.now() - lastExecution > interval) {
  52. window.setTimeout(function () {
  53. const expandedVideos = document.querySelectorAll('.expandedWebm');
  54. for (const video of expandedVideos) {
  55. initVideoElement(video);
  56. if (video.paused && isVisible(video) && !pausedByUser(video)) {
  57. video.play().catch(() => {/* noop */});
  58. }
  59. }
  60. }, interval);
  61. lastExecution = Date.now();
  62. }
  63. });
  64. })();