Island Audio Island Audio
Исходный код

Как работает автоскип YouTube

Ниже показана основная часть Скрипт-кода, которая ищет рекламу, находит кнопку «Пропустить» и помогает нажать её

AUTO_SKIP_SCRIPT = r"""
(() => {
  const normalizeText = (value) => String(value || '').trim().toLowerCase();
  const isVisible = (element) => {
    if (!element) return false;
    const rect = element.getBoundingClientRect();
    if (!rect || rect.width < 8 || rect.height < 8) return false;
    const style = getComputedStyle(element);
    return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0.02;
  };

  const getClickableTarget = (element) => {
    if (!element) return null;
    return element.closest('button,[role="button"],tp-yt-paper-button,.ytp-ad-skip-button,.ytp-ad-overlay-close-button,.ytp-ad-overlay-close-container') || element;
  };

  const buildTargetInfo = (element, kind) => {
    const host = getClickableTarget(element);
    if (!isVisible(host)) return null;
    const rect = host.getBoundingClientRect();
    return {
      kind,
      x: rect.left + rect.width / 2,
      y: rect.top + rect.height / 2,
      width: rect.width,
      height: rect.height,
      text: normalizeText(host.innerText || host.textContent || host.getAttribute('aria-label') || ''),
    };
  };

  const firstVisibleMatch = (selectors) => {
    for (const selector of selectors) {
      const elements = Array.from(document.querySelectorAll(selector));
      for (const element of elements) {
        const info = buildTargetInfo(element, 'selector');
        if (info) return info;
      }
    }
    return null;
  };

  const textButtonMatch = (matcher, kind) => {
    const candidates = Array.from(document.querySelectorAll('button,[role="button"],tp-yt-paper-button'));
    for (const element of candidates) {
      const text = normalizeText(element.innerText || element.textContent || element.getAttribute('aria-label') || '');
      if (!text || !matcher.test(text)) continue;
      const info = buildTargetInfo(element, kind);
      if (info) return info;
    }
    return null;
  };

  const skipSelectors = [
    '.ytp-skip-ad-button',
    '.ytp-ad-skip-button',
    '.ytp-ad-skip-button-modern',
    '.ytp-skip-ad-button-modern',
    '.ytp-skip-ad-button__text',
    'button.ytp-skip-ad-button',
    'button.ytp-ad-skip-button',
    '[aria-label*="Skip"]',
    '[aria-label*="Пропустить"]',
    '[aria-label*="skip"]',
    '[title*="Skip"]',
    '[title*="Пропустить"]'
  ];

  const closeSelectors = [
    '.ytp-ad-overlay-close-button',
    '.ytp-ad-overlay-close-container',
    'button[aria-label*="Close ad"]',
    'button[aria-label*="Закрыть"]',
    '[aria-label*="close ad"]'
  ];

  const skipTarget =
    firstVisibleMatch(skipSelectors) ||
    textButtonMatch(/^(skip ad|skip ads|пропустить|пропустить рекламу|skip)$/i, 'text');

  const closeTarget =
    firstVisibleMatch(closeSelectors) ||
    textButtonMatch(/^(close ad|закрыть|закрыть рекламу)$/i, 'close');

  let overlayClosed = false;
  if (!skipTarget && closeTarget) {
    overlayClosed = true;
  }

  const adShowing =
    document.querySelector('.ad-showing') !== null ||
    document.querySelector('.ytp-ad-player-overlay') !== null ||
    document.querySelector('.video-ads') !== null;

  return {
    skipped: Boolean(skipTarget),
    overlayClosed,
    adShowing,
    href: location.href,
    skipTarget,
    closeTarget
  };
})()
"""
def _evaluate_skip_script(self) -> dict | None:
    response = self._send_command(
        "Runtime.evaluate",
        {
            "expression": AUTO_SKIP_SCRIPT,
            "returnByValue": True,
            "awaitPromise": False,
        },
    )
    if not response:
        return None
    result = response.get("result", {})
    result_value = result.get("result", {}).get("value")
    return result_value if isinstance(result_value, dict) else {}


def _dispatch_click(self, x: float, y: float) -> bool:
    if self._socket is None:
        return False
    self._send_command("Page.bringToFront", {}, wait=False)
    click_x = max(1.0, float(x))
    click_y = max(1.0, float(y))
    events = (
        {"type": "mouseMoved", "x": click_x, "y": click_y, "button": "none", "buttons": 1},
        {"type": "mousePressed", "x": click_x, "y": click_y, "button": "left", "buttons": 1, "clickCount": 1},
        {"type": "mouseReleased", "x": click_x, "y": click_y, "button": "left", "buttons": 0, "clickCount": 1},
    )
    for params in events:
        response = self._send_command("Input.dispatchMouseEvent", params, wait=True, timeout=0.9)
        if response is None or "error" in response:
            return False
    return True
Что делает код

Что именно делает этот Script-code

Этот код ищет рекламу в YouTube, проверяет, появилась ли кнопка «Пропустить», и если находит её, пытается нажать через DevTools-клик по координатам кнопки

Открытый код

Этот код открыт

Премиум даёт только более удобный запуск этой функции внутри Island Audio Если не хотите покупать премиум, вы можете запускать этот код сами Для запуска подойдёт Python 3.11 или новее