Block ads on Youtube

Ad blocker userscript for Youtube

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @license				MIT
// @copyright           Copyright (c) 2019, Romain Lebesle <[email protected]> (https://thoughtsunificator.me)
// @namespace           http://thoughtsunificator.me
// @name                Block ads on Youtube
// @author				Romain Lebesle <[email protected]> (https://thoughtsunificator.me)
// @supportURL          http://thoughtsunificator.me/
// @version             1.2
// @description         Ad blocker userscript for Youtube
// @run-at 				document-start
// @include             https://*.youtube.com/*
// @grant			    GM_addStyle
// ==/UserScript==

GM_addStyle(`
#player-ads,
.adDisplay,
.ad-container,
.ytd-display-ad-renderer,
.video-ads,
#masthead-ad {
	display: none !important;
}
`);

let video

const observer = new MutationObserver(mutations => {
	for(const mutation of mutations) {
		for(const addedNode of mutation.addedNodes) {
			if(addedNode.className && (addedNode.classList.contains("ytp-ad-skip-button-slot") || addedNode.classList.contains("ytp-ad-overlay-close-button"))) {
				console.log("ytp-ad")
				addedNode.click()
			} else if(addedNode.className && addedNode.classList.contains("ad-showing")) {
				console.log("ad-showing")
				if(!isNaN(video.duration)) {
					video.play()
					video.currentTime = video.duration
				}
			} else if(addedNode.tagName === "VIDEO" && addedNode.classList.contains("html5-main-video")) {
				console.log("video")
				video = addedNode
				video.addEventListener("durationupdate", () => {
					console.log("durationupdate")
					video.play()
					video.currentTime = video.duration
				})
				video.addEventListener("timeupdate", () => {
					const adSkipButton = document.querySelector(".ytp-ad-skip-button-slot button,.ytp-ad-overlay-close-button")
					if(adSkipButton) {
						adSkipButton.click()
					}
					if(document.querySelector(".ad-showing")) {
						if(!isNaN(video.duration)) {
							video.play()
							video.currentTime = video.duration
						}
					}
				})
			}
		}
	}
})

observer.observe(document.documentElement, { subtree: true, childList: true, attributes: true })