ShareShortcuts

Block YouTube Ads (by AdGuard)

A Shortcut made by AdGuard

outlander-2007
Fork “Block YouTube Ads (by AdGuard)”

Built something new on top of this Shortcut? Share it as a fork: it becomes a Shortcut of your own, which you manage, and both pages link to each other so outlander-2007 gets credit.

  1. 1Get the Shortcut and change it in the Shortcuts app. Give it a name of its own.
  2. 2Share it from the Shortcuts app and copy the iCloud link.
  3. 3Come back here, paste the link and describe what is different, e.g. “Added a step that uses Apple Intelligence to personalise the text.”
Downloads
71K
Saved
3
Actions
2
Category
Utilities
Version
1.0
Language
EN

A Shortcut made by AdGuard

What's New

Version 1.0

First release

Version History
1.0 Mar 23, 2022

First release

What it does

2 actions
  1. Run JavaScript on Web Page
  2. Show Alert

View as code
Beta

Every action of this Shortcut written out as Cherri, a programming language for Shortcuts. Great for learning how it works.

#include 'actions/web'
#define color red
#define glyph play

runJavaScriptOnWebpage("/**\n * This file is part of AdGuard's Block YouTube Ads (https://github.com/AdguardTeam/BlockYouTubeAdsShortcut).\n *\n * AdGuard's Block YouTube Ads is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * AdGuard's Block YouTube Ads is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with AdGuard's Block YouTube Ads.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/* global Response, window, navigator, document, MutationObserver, completion */\n\n/**\n * Note that Shortcut scripts are executed in their own context (window)\n * and we don't have direct access to the real page window.\n *\n * In order to overcome this, we add a \"script\" to the page which is\n * executed in the proper context. The script content is inside\n * the \"pageScript\" function.\n */\n(() => {\n    // \"completion\" function is only defined if this script is launched as Shortcut\n    // in other cases we simply polyfill it.\n    let finish = (m) => { console.log(m); };\n    if (typeof completion !== 'undefined') {\n        finish = completion;\n    }\n\n    const locales = {\n        en: {\n            logo: 'with&nbsp;AdGuard',\n            alreadyExecuted: 'The shortcut has already been executed.',\n            wrongDomain: 'This shortcut is supposed to be launched only on YouTube.',\n            success: 'YouTube is now ad-free! Please note that you need to run this shortcut again if you reload the page.',\n        },\n        ru: {\n            logo: 'с&nbsp;AdGuard',\n            alreadyExecuted: 'Быстрая команда уже выполнена.',\n            wrongDomain: 'Эта быстрая команда предназначена для использования только на YouTube.',\n            success: 'Теперь YouTube без рекламы! Важно: при перезагрузке страницы вам нужно будет заново запустить команду.',\n        },\n        es: {\n            logo: 'con&nbsp;AdGuard',\n            alreadyExecuted: 'El atajo ya ha sido ejecutado.',\n            wrongDomain: 'Se supone que este atajo se lanza sólo en YouTube.',\n            success: '¡YouTube está ahora libre de anuncios! Ten en cuenta que tienes que volver a ejecutar este atajo si recargas la página.',\n        },\n        de: {\n            logo: 'mit&nbsp;AdGuard',\n            alreadyExecuted: 'Der Kurzbefehl wurde bereits ausgeführt.',\n            wrongDomain: 'Dieser Kurzbefehl soll nur auf YouTube gestartet werden.',\n            success: 'YouTube ist jetzt werbefrei! Bitte beachten Sie, dass Sie diesen Kurzbefehl erneut ausführen müssen, wenn Sie die Seite neu laden.',\n        },\n        fr: {\n            logo: 'avec&nbsp;AdGuard',\n            alreadyExecuted: 'Le raccourci a déjà été exécuté.',\n            wrongDomain: 'Ce raccourci est censé d’être lancé uniquement sur YouTube.',\n            success: 'YouTube est maintenant libre de pub ! Veuillez noter qu’il faudra rééxecuter le raccourci si vous rechargez la page.',\n        },\n        it: {\n            logo: 'con&nbsp;AdGuard',\n            alreadyExecuted: 'Il comando è già stato eseguito.',\n            wrongDomain: 'Questa scorciatoia dovrebbe essere lanciata solo su YouTube.',\n            success: 'YouTube è ora libero da pubblicità! Si prega di notare che è necessario eseguire nuovamente questa scorciatoia se ricarichi la pagina.',\n        },\n        'zh-cn': {\n            logo: '使用&nbsp;AdGuard',\n            alreadyExecuted: '快捷指令已在运行',\n            wrongDomain: '快捷指令只能在 YouTube 上被启动。',\n            success: '现在您的 YouTube 没有广告!请注意,若您重新加载页面,您需要再次启动快捷指令。',\n        },\n        'zh-tw': {\n            logo: '偕同&nbsp;AdGuard',\n            alreadyExecuted: '此捷徑已被執行。',\n            wrongDomain: '此捷徑應該只於 YouTube 上被啟動。',\n            success: '現在 YouTube 為無廣告的!請注意,若您重新載入該頁面,您需要再次執行此捷徑。',\n        },\n        ko: {\n            logo: 'AdGuard&nbsp;사용',\n            alreadyExecuted: '단축어가 이미 실행되었습니다.',\n            wrongDomain: '이 단축어는 YouTube에서만 사용 가능합니다.',\n            success: '이제 광고없이 YouTube를 시청할 수 있습니다. 페이지를 새로고침 할 경우, 이 단축어를 다시 실행해야 합니다.',\n        },\n        ja: {\n            logo: 'AdGuard作動中',\n            alreadyExecuted: 'ショートカットは既に実行されています。',\n            wrongDomain: '※このショートカットは、YouTubeでのみ適用されることを想定しています。',\n            success: 'YouTubeが広告なしになりました!※YouTubeページを再読み込みした場合は、このショートカットを再度実行する必要がありますのでご注意ください。',\n        },\n        uk: {\n            logo: 'з&nbsp;AdGuard',\n            alreadyExecuted: 'Ця швидка команда вже виконується.',\n            wrongDomain: 'Цю швидку команду слід запускати лише на YouTube.',\n            success: 'Тепер YouTube без реклами! Проте після перезавантаження сторінки необхідно знову запустити цю швидку команду.',\n        },\n    };\n\n    /**\n     * Gets a localized message for the specified key\n     *\n     * @param {string} key message key\n     * @returns {string} message for that key\n     */\n    const getMessage = (key) => {\n        try {\n            let locale = locales[navigator.language.toLowerCase()];\n            if (!locale) {\n                const lang = navigator.language.split('-')[0];\n                locale = locales[lang];\n            }\n            if (!locale) {\n                locale = locales.en;\n            }\n\n            return locale[key];\n        } catch (ex) {\n            return locales.en[key];\n        }\n    };\n\n    if (document.getElementById('block-youtube-ads-logo')) {\n        finish(getMessage('alreadyExecuted'));\n        return;\n    }\n\n    if (window.location.hostname !== 'www.youtube.com'\n        && window.location.hostname !== 'm.youtube.com'\n        && window.location.hostname !== 'music.youtube.com') {\n        finish(getMessage('wrongDomain'));\n        return;\n    }\n\n    /**\n     * This function will be executed in the page context\n     */\n    const pageScript = () => {\n        const LOGO_ID = 'block-youtube-ads-logo';\n\n        const hiddenCSS = {\n            'www.youtube.com': [\n                '#__ffYoutube1',\n                '#__ffYoutube2',\n                '#__ffYoutube3',\n                '#__ffYoutube4',\n                '#feed-pyv-container',\n                '#feedmodule-PRO',\n                '#homepage-chrome-side-promo',\n                '#merch-shelf',\n                '#offer-module',\n                '#pla-shelf > ytd-pla-shelf-renderer[class=\"style-scope ytd-watch\"]',\n                '#pla-shelf',\n                '#premium-yva',\n                '#promo-info',\n                '#promo-list',\n                '#promotion-shelf',\n                '#related > ytd-watch-next-secondary-results-renderer > #items > ytd-compact-promoted-video-renderer.ytd-watch-next-secondary-results-renderer',\n                '#search-pva',\n                '#shelf-pyv-container',\n                '#video-masthead',\n                '#watch-branded-actions',\n                '#watch-buy-urls',\n                '#watch-channel-brand-div',\n                '#watch7-branded-banner',\n                '#YtKevlarVisibilityIdentifier',\n                '#YtSparklesVisibilityIdentifier',\n                '.carousel-offer-url-container',\n                '.companion-ad-container',\n                '.GoogleActiveViewElement',\n                '.list-view[style=\"margin: 7px 0pt;\"]',\n                '.promoted-sparkles-text-search-root-container',\n                '.promoted-videos',\n                '.searchView.list-view',\n                '.sparkles-light-cta',\n                '.watch-extra-info-column',\n                '.watch-extra-info-right',\n                '.ytd-carousel-ad-renderer',\n                '.ytd-compact-promoted-video-renderer',\n                '.ytd-companion-slot-renderer',\n                '.ytd-merch-shelf-renderer',\n                '.ytd-player-legacy-desktop-watch-ads-renderer',\n                '.ytd-promoted-sparkles-text-search-renderer',\n                '.ytd-promoted-video-renderer',\n                '.ytd-search-pyv-renderer',\n                '.ytd-video-masthead-ad-v3-renderer',\n                '.ytp-ad-action-interstitial-background-container',\n                '.ytp-ad-action-interstitial-slot',\n                '.ytp-ad-image-overlay',\n                '.ytp-ad-overlay-container',\n                '.ytp-ad-progress',\n                '.ytp-ad-progress-list',\n                '[class*=\"ytd-display-ad-\"]',\n                '[layout*=\"display-ad-\"]',\n                'a[href^=\"http://www.youtube.com/cthru?\"]',\n                'a[href^=\"https://www.youtube.com/cthru?\"]',\n                'ytd-action-companion-ad-renderer',\n                'ytd-banner-promo-renderer',\n                'ytd-compact-promoted-video-renderer',\n                'ytd-companion-slot-renderer',\n                'ytd-display-ad-renderer',\n                'ytd-promoted-sparkles-text-search-renderer',\n                'ytd-promoted-sparkles-web-renderer',\n                'ytd-search-pyv-renderer',\n                'ytd-single-option-survey-renderer',\n                'ytd-video-masthead-ad-advertiser-info-renderer',\n                'ytd-video-masthead-ad-v3-renderer',\n                'YTM-PROMOTED-VIDEO-RENDERER',\n            ],\n            'm.youtube.com': [\n                '.companion-ad-container',\n                '.ytp-ad-action-interstitial',\n                '.ytp-cued-thumbnail-overlay > div[style*=\"/sddefault.jpg\"]',\n                'a[href^=\"/watch?v=\"][onclick^=\"return koya.onEvent(arguments[0]||window.event,\'\"]:not([role]):not([class]):not([id])',\n                'a[onclick*=\'\"ping_url\":\"http://www.google.com/aclk?\']',\n                'ytm-companion-ad-renderer',\n                'ytm-companion-slot',\n                'ytm-promoted-sparkles-text-search-renderer',\n                'ytm-promoted-sparkles-web-renderer',\n                'ytm-promoted-video-renderer',\n            ],\n        };\n\n        /**\n         * Adds CSS to the page\n         * @param {string} hostname hostname\n         */\n        const hideElements = (hostname) => {\n            const selectors = hiddenCSS[hostname];\n            if (!selectors) {\n                return;\n            }\n            const rule = `${selectors.join(', ')} { display: none!important; }`;\n            const style = document.createElement('style');\n            style.innerHTML = rule;\n            document.head.appendChild(style);\n        };\n\n        /**\n         * Calls the \"callback\" function on every DOM change, but not for the tracked events\n         * @param {Function} callback callback function\n         */\n        const observeDomChanges = (callback) => {\n            const domMutationObserver = new MutationObserver((mutations) => {\n                callback(mutations);\n            });\n\n            domMutationObserver.observe(document.documentElement, {\n                childList: true,\n                subtree: true,\n            });\n        };\n\n        /**\n         * This function is supposed to be called on every DOM change\n         */\n        const hideDynamicAds = () => {\n            const elements = document.querySelectorAll('#contents > ytd-rich-item-renderer ytd-display-ad-renderer');\n            if (elements.length === 0) {\n                return;\n            }\n            elements.forEach((el) => {\n                if (el.parentNode && el.parentNode.parentNode) {\n                    const parent = el.parentNode.parentNode;\n                    if (parent.localName === 'ytd-rich-item-renderer') {\n                        parent.style.display = 'none';\n                    }\n                }\n            });\n        };\n\n        /**\n         * This function checks if the video ads are currently running\n         * and auto-clicks the skip button.\n         */\n        const autoSkipAds = () => {\n            // If there's a video that plays the ad at this moment, scroll this ad\n            if (document.querySelector('.ad-showing')) {\n                const video = document.querySelector('video');\n                if (video && video.duration) {\n                    video.currentTime = video.duration;\n                    // Skip button should appear after that,\n                    // now simply click it automatically\n                    setTimeout(() => {\n                        const skipBtn = document.querySelector('button.ytp-ad-skip-button');\n                        if (skipBtn) {\n                            skipBtn.click();\n                        }\n                    }, 100);\n                }\n            }\n        };\n\n        /**\n         * This function overrides a property on the specified object.\n         *\n         * @param {object} obj object to look for properties in\n         * @param {string} propertyName property to override\n         * @param {*} overrideValue value to set\n         */\n        const overrideObject = (obj, propertyName, overrideValue) => {\n            if (!obj) {\n                return false;\n            }\n            let overriden = false;\n\n            for (const key in obj) {\n                if (obj.hasOwnProperty(key) && key === propertyName) {\n                    obj[key] = overrideValue;\n                    overriden = true;\n                } else if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') {\n                    if (overrideObject(obj[key], propertyName, overrideValue)) {\n                        overriden = true;\n                    }\n                }\n            }\n\n            if (overriden) {\n                console.log(`found: ${propertyName}`);\n            }\n\n            return overriden;\n        };\n\n        /**\n         * Overrides JSON.parse and Response.json functions.\n         * Examines these functions arguments, looks for properties with the specified name there\n         * and if it exists, changes it's value to what was specified.\n         *\n         * @param {string} propertyName name of the property\n         * @param {*} overrideValue new value for the property\n         */\n        const jsonOverride = (propertyName, overrideValue) => {\n            const nativeJSONParse = JSON.parse;\n            JSON.parse = (...args) => {\n                const obj = nativeJSONParse.apply(this, args);\n\n                // Override it's props and return back to the caller\n                overrideObject(obj, propertyName, overrideValue);\n                return obj;\n            };\n\n            // Override Response.prototype.json\n            const nativeResponseJson = Response.prototype.json;\n            Response.prototype.json = new Proxy(nativeResponseJson, {\n                apply(...args) {\n                    // Call the target function, get the original Promise\n                    const promise = Reflect.apply(args);\n\n                    // Create a new one and override the JSON inside\n                    return new Promise((resolve, reject) => {\n                        promise.then((data) => {\n                            overrideObject(data, propertyName, overrideValue);\n                            resolve(data);\n                        }).catch((error) => reject(error));\n                    });\n                },\n            });\n        };\n\n        const addAdGuardLogoStyle = () => {\n            const id = 'block-youtube-ads-logo-style';\n            if (document.getElementById(id)) {\n                return;\n            }\n\n            // Here is what these styles do:\n            // 1. Change AG marker color depending on the page\n            // 2. Hide Sign-in button on m.youtube.com otherwise it does not look good\n            // It is still possible to sign in by clicking \"three dots\" button.\n            // 3. Hide the marker when the user is searching for something\n            // 4. On YT Music apply display:block to the logo element\n            const style = document.createElement('style');\n            style.innerHTML = `[data-mode=\"watch\"] #${LOGO_ID} { color: #fff; }\n[data-mode=\"searching\"] #${LOGO_ID}, [data-mode=\"search\"] #${LOGO_ID} { display: none; }\n#${LOGO_ID} { white-space: nowrap; }\n.mobile-topbar-header-sign-in-button { display: none; }\n.ytmusic-nav-bar#left-content #${LOGO_ID} { display: block; }`;\n            document.head.appendChild(style);\n        };\n\n        const addAdGuardLogo = () => {\n            if (document.getElementById(LOGO_ID)) {\n                return;\n            }\n\n            const logo = document.createElement('span');\n            logo.innerHTML = '__logo_text__';\n            logo.setAttribute('id', LOGO_ID);\n\n            if (window.location.hostname === 'm.youtube.com') {\n                const btn = document.querySelector('header.mobile-topbar-header > button');\n                if (btn) {\n                    btn.parentNode.insertBefore(logo, btn.nextSibling);\n                    addAdGuardLogoStyle();\n                }\n            } else if (window.location.hostname === 'www.youtube.com') {\n                const code = document.getElementById('country-code');\n                if (code) {\n                    code.innerHTML = '';\n                    code.appendChild(logo);\n                    addAdGuardLogoStyle();\n                }\n            } else if (window.location.hostname === 'music.youtube.com') {\n                const el = document.querySelector('.ytmusic-nav-bar#left-content');\n                if (el) {\n                    el.appendChild(logo);\n                    addAdGuardLogoStyle();\n                }\n            }\n        };\n\n        // Removes ads metadata from YouTube XHR requests\n        jsonOverride('adPlacements', []);\n        jsonOverride('playerAds', []);\n\n        // Applies CSS that hides YouTube ad elements\n        hideElements(window.location.hostname);\n\n        // Some changes should be re-evaluated on every page change\n        addAdGuardLogo();\n        hideDynamicAds();\n        autoSkipAds();\n        observeDomChanges(() => {\n            addAdGuardLogo();\n            hideDynamicAds();\n            autoSkipAds();\n        });\n    };\n\n    const script = document.createElement('script');\n    const scriptText = pageScript.toString().replace('__logo_text__', getMessage('logo'));\n    script.innerHTML = `(${scriptText})();`;\n    document.head.appendChild(script);\n    document.head.removeChild(script);\n\n    finish(getMessage('success'));\n})();\n")
alert(, "")
Decompiled with cherri 2.3.0 (GPL-2.0). May need small fixes before it compiles.

Ratings & Reviews

Write a Review
–
out of 5
★★★★★
★★★★
★★★
★★
★
0 ratings

No reviews yet. Be the first to share what you think!

Advertisement

More by outlander-2007

See All

You Might Also Like

See All
Advertisement