Auto Close Youtube Popup Ads

Closes youtubes ads automatically after a small pause

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

// ==UserScript==
// @name         Auto Close Youtube Popup Ads
// @namespace    http://fuzetsu.acypa.com
// @version      1.0.0
// @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 Popup Ads';
var SEC_WAIT = 3;
var ticks = [];

function log() {
  var args = [].slice.call(arguments);
  args.unshift('%cAuto Close Youtube Popup Ads:', 'font-weight: bold');
  console.log.apply(console, args);
}

function clearTicks(ticks) {
  ticks.forEach(function(tick) {
    clearInterval(tick);
  });
}

function keepTrying(wait, action) {
  var tick = setInterval(function() {
    if(action()) {
      clearInterval(tick);
    }
  }, wait);
}

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

log('Started');

waitForUrl(/^https:\/\/www.youtube.com\/watch\?v=.+/, function() {
  clearTicks(ticks);
  log('Entered video, watching for ads');
  ticks.push(
    waitAndClick('.videoAdUiSkipButton', function(btn) {
      keepTrying(1000, function() {
        btn.click();
        if(!document.querySelector('.videoAdUiSkipButton')) {
          return true;
        }
      });
    }),
    waitAndClick('div.close-button', function(btn) {
      document.querySelector('div.recall-button').remove();
    })
  );
});