aboutsummaryrefslogtreecommitdiff
path: root/qute/dot-config/qutebrowser/greasemonkey/yt-ads.js
blob: db98c6baa3021d649ac26a266b3edcded07a3d31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// ==UserScript==
// for more updated scripts, see: https://greasyfork.org/en/scripts/by-site/youtube.com
// @name         Auto Skip YouTube Ads
// @version      1.1.0
// @description  Speed up and skip YouTube ads automatically
// @author       jso8910 and others
// @match        *://*.youtube.com/*
// ==/UserScript==

// NOTE: this is the previous version I had
// document.addEventListener('load', () => {
//     const btn = document.querySelector('.videoAdUiSkipButton,.ytp-ad-skip-button-modern')
//     if (btn) {
//         btn.click()
//     }
//     const ad = [...document.querySelectorAll('.ad-showing')][0];
//     if (ad) {
//         document.querySelector('video').currentTime = 9999999999;
//     }
// }, true);


// this newer version is from
// https://greasyfork.org/en/scripts/553239-auto-skip-youtube-ads/

function skipAd() {
    if (checkIsYouTubeShorts()) return

    // This element appears when a video ad appears.
    const adShowing = document.querySelector('.ad-showing')

    // Timed pie countdown ad.
    const pieCountdown = document.querySelector('.ytp-ad-timed-pie-countdown-container')

    // Survey questions in video player.
    const surveyQuestions = document.querySelector('.ytp-ad-survey-questions')

    if (adShowing === null && pieCountdown === null && surveyQuestions === null) return

    const moviePlayerEl = document.querySelector('#movie_player')
    let playerEl
    let player

    if (isYouTubeMobile || isYouTubeMusic) {
        playerEl = moviePlayerEl
        player = playerEl
    } else {
        playerEl = document.querySelector('#ytd-player')
        player = playerEl && playerEl.getPlayer()
    }

    if (playerEl === null || player === null) {
        console.log({
            message: 'Player not found',
            timeStamp: getCurrentTimeString()
        })
        return
    }

    // ad.classList.remove('ad-showing')

    let adVideo = null

    if (pieCountdown === null && surveyQuestions === null) {
        adVideo = document.querySelector(
            '#ytd-player video.html5-main-video, #song-video video.html5-main-video'
        )

        console.table({
            message: 'Ad video',
            video: adVideo !== null,
            src: adVideo?.src,
            paused: adVideo?.paused,
            currentTime: adVideo?.currentTime,
            duration: adVideo?.duration,
            timeStamp: getCurrentTimeString()
        })

        if (adVideo !== null) {
            adVideo.muted = true
        }
        if (adVideo === null || !adVideo.src || adVideo.paused || isNaN(adVideo.duration)) {
            return
        }

        console.log({
            message: 'Ad video has finished loading',
            timeStamp: getCurrentTimeString()
        })
    }

    if (isYouTubeMusic && adVideo !== null) {
        adVideo.currentTime = adVideo.duration

        console.table({
            message: 'Ad skipped',
            timeStamp: getCurrentTimeString(),
            adShowing: adShowing !== null,
            pieCountdown: pieCountdown !== null,
            surveyQuestions: surveyQuestions !== null
        })
    } else {
        const videoData = player.getVideoData()
        const videoId = videoData.video_id
        const start = Math.floor(player.getCurrentTime())

        if (moviePlayerEl !== null && moviePlayerEl.isSubtitlesOn()) {
            window.setTimeout(moviePlayerEl.toggleSubtitlesOn, 1000)
        }

        if ('loadVideoWithPlayerVars' in playerEl) {
            playerEl.loadVideoWithPlayerVars({ videoId, start })
        } else {
            playerEl.loadVideoByPlayerVars({ videoId, start })
        }

        console.table({
            message: 'Ad skipped',
            videoId,
            start,
            title: videoData.title,
            timeStamp: getCurrentTimeString(),
            adShowing: adShowing !== null,
            pieCountdown: pieCountdown !== null,
            surveyQuestions: surveyQuestions !== null
        })
    }
}

function checkIsYouTubeShorts() {
    return location.pathname.startsWith('/shorts/')
}

function getCurrentTimeString() {
    return new Date().toTimeString().split(' ', 1)[0]
}

function addCss() {
    const adsSelectors = [
        // Ad banner in the upper right corner, above the video playlist.
        '#player-ads',
        '#panels > ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-ads"]',

        // Masthead ad on home page.
        '#masthead-ad',

        // Sponsored ad video items on home page.
        // 'ytd-ad-slot-renderer',

        // '.ytp-suggested-action',
        '.yt-mealbar-promo-renderer',

        // Featured product ad banner at the bottom left of the video.
        '.ytp-featured-product',

        // Products shelf ad banner below the video description.
        'ytd-merch-shelf-renderer',

        // YouTube Music Premium trial promotion dialog, bottom left corner.
        'ytmusic-mealbar-promo-renderer',

        // YouTube Music Premium trial promotion banner on home page.
        'ytmusic-statement-banner-renderer'
    ]
    const adsSelector = adsSelectors.join(',')
    const css = `${adsSelector} { display: none !important; }`
    const style = document.createElement('style')
    style.textContent = css
    document.head.appendChild(style)
}

/**
 * Remove ad elements using JavaScript because these selectors require the use of the CSS
 * `:has` selector which is not supported in older browser versions.
 */
function removeAdElements() {
    const adSelectors = [
        // Sponsored ad video items on home page.
        // ['ytd-rich-item-renderer', '.ytd-ad-slot-renderer'],

        // ['ytd-rich-section-renderer', '.ytd-statement-banner-renderer'],

        // Ad videos on YouTube Shorts.
        ['ytd-reel-video-renderer', '.ytd-ad-slot-renderer']

        // Ad blocker warning dialog.
        // ['tp-yt-paper-dialog', '#feedback.ytd-enforcement-message-view-model'],

        // Survey dialog on home page, located at bottom right.
        // ['tp-yt-paper-dialog', ':scope > ytd-checkbox-survey-renderer'],

        // Survey to rate suggested content, located at bottom right.
        // ['tp-yt-paper-dialog', ':scope > ytd-single-option-survey-renderer']
    ]
    for (const adSelector of adSelectors) {
        const adEl = document.querySelector(adSelector[0])
        if (adEl === null) continue
        const neededEl = adEl.querySelector(adSelector[1])
        if (neededEl === null) continue
        adEl.remove()
    }
}

const isYouTubeMobile = location.hostname === 'm.youtube.com'
const isYouTubeDesktop = !isYouTubeMobile

const isYouTubeMusic = location.hostname === 'music.youtube.com'
const isYouTubeVideo = !isYouTubeMusic

addCss()

if (isYouTubeVideo) {
window.setInterval(removeAdElements, 1000)
removeAdElements()
}

window.setInterval(skipAd, 500)
skipAd()


// const observer = new MutationObserver(skipAd)
// observer.observe(document.body, {
// 	attributes: true,
// 	attributeFilter: ['class'],
// 	childList: true,
// 	subtree: true
// })