Auto Close YouTube Ads

Closes youtubes ads automatically after a small pause

As of 2015-04-14. See the latest version.

// ==UserScript==
// @name         Auto Close YouTube Ads
// @namespace    http://fuzetsu.acypa.com
// @version      1.0.4
// @description  Closes youtubes ads automatically after a small pause
// @author       fuzetsu
// @match        https://www.youtube.com/*
// @grant        none
// @require      https://greasyfork.org/scripts/5679-wait-for-elements/code/Wait%20For%20Elements.js
// @noframes
// ==/UserScript==

var SCRIPT_NAME = 'Auto Close YouTube Ads';
var SEC_WAIT = 3;
var ticks = [];
var videoUrl;

var Util = {
  log: function () {
    var args = [].slice.call(arguments);
    args.unshift('%c' + SCRIPT_NAME + ':', 'font-weight: bold;color: purple;');
    console.log.apply(console, args);
  },
  clearTicks: function(ticks) {
    ticks.forEach(function(tick) {
      clearInterval(tick);
    });
    ticks.length = 0;
  },
  keepTrying: function(wait, action) {
    var tick = setInterval(function() {
      if(action()) {
        clearInterval(tick);
      }
    }, wait);
  },
  q: function(query, context) {
    return (context || document).querySelector(query);
  },
  qq: function(query, context) {
    return [].slice.call((context || document).querySelectorAll(query));
  }
};

function waitAndClick(sel, cb, extraWait) {
  return waitForElems(sel, function(btn) {
    Util.log('Found ad, closing in', SEC_WAIT, 'seconds');
    setTimeout(function() {
      btn.click();
      if(cb) {
        cb(btn);
      }
    }, SEC_WAIT * 1000 + (extraWait || 0));
  }); 
}

Util.log('Started');

waitForUrl(/^https:\/\/www.youtube.com\/watch\?v=.+/, function() {
  if(videoUrl && location.href !== videoUrl) {
    Util.log('Changed video, removing old wait');
    Util.clearTicks(ticks);
  }
  videoUrl = location.href;
  Util.log('Entered video, waiting for ads');
  ticks.push(
    waitAndClick('.videoAdUiSkipButton', function(btn) {
      Util.keepTrying(1000, function() {
        btn.click();
        if(!Util.q('.videoAdUiSkipButton')) {
          return true;
        }
      });
    }),
    waitAndClick('div.close-button', function(btn) {
      Util.q('div.recall-button').remove();
    }),
    waitForUrl(function(url) {
      return url !== videoUrl;
    }, function() {
      videoUrl = null;
      Util.clearTicks(ticks);
      Util.log('Left video, stopped waiting for ads');
    }, true)
  );
});