YouTube Ad Blocker

Block YouTube ads effectively

  1. // ==UserScript==
  2. // @name YouTube Ad Blocker
  3. // @namespace http://tampermonkey.net/
  4. // @version 3.0
  5. // @description Block YouTube ads effectively
  6. // @author Patrick
  7. // @match https://*.youtube.com/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
  9. // @grant none
  10. // @run-at document-start
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. // Patches the ads for cold loading
  15. var ytInitialPlayerResponse = null;
  16.  
  17. function getter() {
  18. return ytInitialPlayerResponse;
  19. }
  20.  
  21. function setter(data) {
  22. ytInitialPlayerResponse = { ...data, adPlacements: [] };
  23. }
  24.  
  25. if (window.ytInitialPlayerResponse) {
  26. Object.defineProperty(window.ytInitialPlayerResponse, 'adPlacements', {
  27. get: () => [],
  28. set: (a) => undefined,
  29. configurable: true
  30. });
  31. } else {
  32. Object.defineProperty(window, 'ytInitialPlayerResponse', {
  33. get: getter,
  34. set: setter,
  35. configurable: true
  36. });
  37. }
  38.  
  39. // FETCH POLYFILL
  40. (function() {
  41. const { fetch: origFetch } = window;
  42. window.fetch = async (...args) => {
  43. const response = await origFetch(...args);
  44.  
  45. if (response.url.includes('/youtubei/v1/player')) {
  46. const text = () =>
  47. response
  48. .clone()
  49. .text()
  50. .then((data) => data.replace(/adPlacements/, 'odPlacement'));
  51.  
  52. response.text = text;
  53. return response;
  54. }
  55. return response;
  56. };
  57. })();
  58.  
  59. // OTHER STUFF - just in case an ad gets through
  60. (function() {
  61. window.autoClick = setInterval(function() {
  62. try {
  63. const btn = document.querySelector('.videoAdUiSkipButton,.ytp-ad-skip-button');
  64. if (btn) {
  65. btn.click();
  66. }
  67. const ad = document.querySelector('.ad-showing');
  68. if (ad) {
  69. document.querySelector('video').playbackRate = 10;
  70. }
  71. } catch (ex) {}
  72. }, 100);
  73.  
  74. window.inlineAdsInterval = setInterval(function() {
  75. try {
  76. const div = document.querySelector('#player-ads');
  77. if (div) {
  78. div.parentNode.removeChild(div);
  79. }
  80. } catch (ex) {}
  81. }, 500);
  82. })();
  83. })();