Skip to content

Instantly share code, notes, and snippets.

@cutiepoka
Created October 6, 2023 18:18
Show Gist options
  • Star 65 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save cutiepoka/a9347c68bfcf29060926a8af46bb1701 to your computer and use it in GitHub Desktop.
Save cutiepoka/a9347c68bfcf29060926a8af46bb1701 to your computer and use it in GitHub Desktop.
Youtube allow ads popup blocker
// ==UserScript==
// @name youtube popup killer
// @namespace http://tampermonkey.net/
// @version 0.3
// @description try to take over the world!
// @author Selbereth
// @match https://*.youtube.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant none
// ==/UserScript==
(function () {
window.debug = true;
if (debug) console.log("started");
setInterval(() => {
if (!!popupFind()) {
if (debug) console.log("remove popup");
const popup = popupFind()
console.log(popup)
popup.parentNode.removeChild(popup)
if (debug) console.log("resume video");
//pauseFind().click()
if (debug) console.log("done ");
}
}, 1000);
})();
function popupFind() {
return document.querySelector("body > ytd-app > ytd-popup-container");
}
function pauseFind(){
return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
}
@ItsProfessional
Copy link

ItsProfessional commented Oct 17, 2023

I have refactored and modified @stevenrlp's latest revision so that it only removes the Anti-Adblock popup, not every popup (e.g. the notifications popup). It also fixes it so that pausing the video with space or k no longer automatically unpauses the video.

(() => {
  let paused_flag = false

  function togglePausedFlag(e) {
    paused_flag = !paused_flag
  }

  function addListeners(pauseButton) {
    pauseButton.addEventListener("click", togglePausedFlag, false)
    pauseButton.addEventListener("keydown", togglePausedFlag, false)
  }

  function removeListeners(pauseButton) {
    pauseButton.removeEventListener("click", togglePausedFlag, false)
    pauseButton.removeEventListener("keydown", togglePausedFlag, false)
  }

  setInterval(() => {
    // if popup is shown, remove it
    let popup = document.querySelector("body > ytd-app > ytd-popup-container > .ytd-popup-container > ytd-enforcement-message-view-model")
    if (popup) popup.parentNode.remove()

    // add an event listener to listen for when the user plays/pauses a video
    // and if it was done automatically by the anti-adblock, unpause the video
    const pauseButton = document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button.ytp-play-button")
    if(pauseButton) {
      let tooltip = pauseButton.getAttribute("data-title-no-tooltip")
      let paused = tooltip == "Play"

      removeListeners(pauseButton) // remove listeners temporarily

      // if video has been paused automatically (not by the user), unpause it
      if(paused && !paused_flag) {
        paused_flag = !paused // update the flag in case it's out of sync somehow
        pauseButton.click()
      }

      addListeners(pauseButton)
    }
  }, 100);
})();

@yxkhkhiw
Copy link

Why you guys make it so hard?

need to test the code

// ==UserScript==
// @name         Fpop
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       none
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(() => {
    setInterval(() => {
        console.log("loop");
        const popup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
        if (popup) {
            const play_bottom = document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
            const play_state = play_bottom.getAttribute("data-title-no-tooltip");

            const overlay = document.querySelector("body > tp-yt-iron-overlay-backdrop");

            if (play_state == "Play") {
                popup.remove();
                console.log("popup");

                overlay.remove();
                console.log("overlay");

                play_bottom.click();
                console.log("auto play");
            }
        }
    }, 1500);
})();

@stevenrlp
Copy link

Why you guys make it so hard?

need to test the code

// ==UserScript==
// @name         Fpop
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       none
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(() => {
    setInterval(() => {
        console.log("loop");
        const popup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
        if (popup) {
            const play_bottom = document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
            const play_state = play_bottom.getAttribute("data-title-no-tooltip");

            const overlay = document.querySelector("body > tp-yt-iron-overlay-backdrop");

            if (play_state == "Play") {
                popup.remove();
                console.log("popup");

                overlay.remove();
                console.log("overlay");

                play_bottom.click();
                console.log("auto play");
            }
        }
    }, 1500);
})();

This seems to work well, good job, I wonder how long until they stop us from bypassing it. :(

@yxkhkhiw
Copy link

yxkhkhiw commented Oct 17, 2023

Why you guys make it so hard?

need to test the code

it seems like they have function that pause video when popup showing up
after popup.remove(); pause function still not deleted,
so code still need fix

@siamak
Copy link

siamak commented Oct 17, 2023

Hey all,

I think it's more cleaner.

const interval = setInterval(() => {
	const popup = popupFind();

	if (popup) {
		const popupParent = popup.parentNode;
		popupParent.removeChild(popup);

		// Uncomment the following line to resume video playback
		// pauseFind().click();
	} else {
		clearInterval(interval); // Clear the interval when the popup is false
	}
}, 1000);

function popupFind() {
	return document.querySelector("body > ytd-app > ytd-popup-container");
}

function pauseFind() {
	return document.querySelector(
		"#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button"
	);
}

@congaterori
Copy link

Why you guys make it so hard?
need to test the code
it seems like they have function that pause video when popup showing up after popup.remove(); pause function still not deleted, so code still need fix

New version, it automaticy hits play after the code run

// ==UserScript==
// @name         Fpop
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Auto-play YouTube videos when a popup is detected
// @author       none
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(() => {
    setInterval(() => {
        const popup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
        if (popup) {
            // Check if the video is paused
            const video = document.querySelector('video');
            if (video && video.paused) {
                // Use the YouTube API to play the video
                video.play();
                console.log("Auto-play");
            }
            // Close the popup
            popup.remove();
            console.log("Popup removed");
        }
    }, 1500);
})();

@yxkhkhiw
Copy link

New version, it automaticy hits play after the code run

👍

@PeterFuciik
Copy link

sup guys,
I found this.. thing? thru official gresemoneky websites. So far it works for on opera gx, no pop ups, no adblockers, no ads.
Its described Chinese so i dont understand nothing.

// ==UserScript==
// @name YouTube去广告 YouTube AD Blocker
// @name:zh-CN YouTube去广告
// @name:zh-TW YouTube去廣告
// @name:zh-HK YouTube去廣告
// @name:zh-MO YouTube去廣告
// @namespace http://tampermonkey.net/
// @Version 5.95
// @description 这是一个去除YouTube广告的脚本,轻量且高效,它能丝滑的去除界面广告和视频广告,包括6s广告。This is a script that removes ads on YouTube, it's lightweight and efficient, capable of smoothly removing interface and video ads, including 6s ads.
// @description:zh-CN 这是一个去除YouTube广告的脚本,轻量且高效,它能丝滑的去除界面广告和视频广告,包括6s广告。
// @description:zh-TW 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
// @description:zh-HK 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
// @description:zh-MO 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
// @author iamfugui
// @match ://.youtube.com/*
// @ICON https://www.google.com/s2/favicons?sz=64&domain=YouTube.com
// @grant none
// @license MIT
// ==/UserScript==
(function() {
use strict;

//界面广告选择器
const cssSeletorArr = [
    `#masthead-ad`,//首页顶部横幅广告.
    `ytd-rich-item-renderer.style-scope.ytd-rich-grid-row #content:has(.ytd-display-ad-renderer)`,//首页视频排版广告.
    `.video-ads.ytp-ad-module`,//播放器底部广告.
    `tp-yt-paper-dialog:has(yt-mealbar-promo-renderer)`,//播放页会员促销广告.
    `ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-ads"]`,//播放页右上方推荐广告.
    `#related #player-ads`,//播放页评论区右侧推广广告.
    `#related ytd-ad-slot-renderer`,//播放页评论区右侧视频排版广告.
    `ytd-ad-slot-renderer`,//搜索页广告.
    `yt-mealbar-promo-renderer`,//播放页会员推荐广告.
    `ad-slot-renderer`,//M播放页第三方推荐广告
    `ytm-companion-ad-renderer`,//M可跳过的视频广告链接处
];

window.dev=true;//开发使用

/**
* 将标准时间格式化
* @param {Date} time 标准时间
* @param {String} format 格式
* @return {String}
*/
function moment(time, format = `YYYY-MM-DD HH:mm:ss`) {
    // 获取年⽉⽇时分秒
    let y = time.getFullYear()
    let m = (time.getMonth() + 1).toString().padStart(2, `0`)
    let d = time.getDate().toString().padStart(2, `0`)
    let h = time.getHours().toString().padStart(2, `0`)
    let min = time.getMinutes().toString().padStart(2, `0`)
    let s = time.getSeconds().toString().padStart(2, `0`)
    if (format === `YYYY-MM-DD`) {
        return `${y}-${m}-${d}`
    } else {
        return `${y}-${m}-${d} ${h}:${min}:${s}`
    }
}

/**
* 输出信息
* @param {String} msg 信息
* @return {undefined}
*/
function log(msg) {
    if(!window.dev){
        return false;
    }
    console.log(`${moment(new Date())}  ${msg}`)
}

/**
* 获取当前url的参数,如果要查询特定参数请传参
* @param {String} 要查询的参数
* @return {String || Object}
*/
function getUrlParams(param) {
    // 通过 ? 分割获取后面的参数字符串
    let urlStr = location.href.split(`?`)[1]
    if(!urlStr){
        return ``;
    }
    // 创建空对象存储参数
    let obj = {};
    // 再通过 & 将每一个参数单独分割出来
    let paramsArr = urlStr.split(`&`)
    for(let i = 0,len = paramsArr.length;i < len;i++){
        // 再通过 = 将每一个参数分割为 key:value 的形式
        let arr = paramsArr[i].split(`=`)
        obj[arr[0]] = arr[1];
    }

    if(!param){
        return obj;
    }

    return obj[param]||``;
}

/**
* 生成去除广告的css元素style并附加到HTML节点上
* @param {String} styles 样式文本
* @return {undefined}
*/
function generateRemoveADHTMLElement(styles) {
    //如果已经设置过,退出.
    if (document.getElementById(`RemoveADHTMLElement`)) {
        log(`屏蔽页面广告节点已生成`);
        return false
    }

    //设置移除广告样式.
    let style = document.createElement(`style`);//创建style元素.
    style.id = `RemoveADHTMLElement`;
    (document.querySelector(`head`) || document.querySelector(`body`)).appendChild(style);//将节点附加到HTML.
    style.appendChild(document.createTextNode(styles));//附加样式节点到元素节点.
    log(`生成屏蔽页面广告节点成功`)

}

/**
* 生成去除广告的css文本
* @param {Array} cssSeletorArr 待设置css选择器数组
* @return {String}
*/
function generateRemoveADCssText(cssSeletorArr){
    cssSeletorArr.forEach((seletor,index)=>{
        cssSeletorArr[index]=`${seletor}{display:none!important}`;//遍历并设置样式.
    });
    return cssSeletorArr.join(` `);//拼接成字符串.
}

/**
* 触摸事件
* @return {undefined}
*/
function nativeTouch(){
    const minNum = 100;
    const maxNum = 999;
    const randomNum = (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum)/1000;

    let element =this;
    // 创建 Touch 对象
    let touch = new Touch({
        identifier: Date.now(),
        target: element,
        clientX: 111+randomNum,
        clientY: 222+randomNum,
        radiusX: 333+randomNum,
        radiusY: 444+randomNum,
        rotationAngle: 0,
        force: 1
    });

    // 创建 TouchEvent 对象
    let touchStartEvent = new TouchEvent("touchstart", {
        bubbles: true,
        cancelable: true,
        view: window,
        touches: [touch],
        targetTouches: [touch],
        changedTouches: [touch]
    });

    // 分派 touchstart 事件到目标元素
    element.dispatchEvent(touchStartEvent);

    // 创建 TouchEvent 对象
    let touchEndEvent = new TouchEvent("touchend", {
        bubbles: true,
        cancelable: true,
        view: window,
        touches: [],
        targetTouches: [],
        changedTouches: [touch]
    });

    // 分派 touchend 事件到目标元素
    element.dispatchEvent(touchEndEvent);
}

/**
* 跳过广告
* @return {undefined}
*/
function skipAd(mutationsList, observer) {
    let video = document.querySelector(`.ad-showing video`) || document.querySelector(`video`);//获取视频节点
    let skipButton = document.querySelector(`.ytp-ad-skip-button`);
    let shortAdMsg = document.querySelector(`.video-ads.ytp-ad-module .ytp-ad-player-overlay`);

    if(!skipButton && !shortAdMsg){
        log(`######广告不存在######`);
        return false;
    }

    //拥有跳过按钮的广告.
    if(skipButton)
    {
        log(`普通视频广告~~~~~~~~~~~~~`);
        log(`总时长:`);
        log(`${video.duration}`)
        log(`当前时间:`);
        log(`${video.currentTime}`)
        // 跳过广告.
        skipButton.click();//PC
        nativeTouch.call(skipButton);//Phone
        log(`按钮跳过了该广告~~~~~~~~~~~~~`);
        return false;//终止
    }

    //没有跳过按钮的短广告.
    if(shortAdMsg){
        log(`强制视频广告~~~~~~~~~~~~~`);
        log(`总时长:`);
        log(`${video.duration}`)
        log(`当前时间:`);
        log(`${video.currentTime}`)
        video.currentTime = video.duration;
        log(`强制结束了该广告~~~~~~~~~~~~~`);
        return false;//终止
    }
}

/**
* 去除播放中的广告
* @return {undefined}
*/
function removePlayerAD(){

    //如果已经在运行,退出.
    if (document.getElementById(`removePlayerAD`)) {
        log(`去除播放中的广告功能已在运行`);
        return false
    }
    //设置运行tag.
    let style = document.createElement(`style`);
    style.id = `removePlayerAD`;
    (document.querySelector(`head`) || document.querySelector(`body`)).appendChild(style);//将节点附加到HTML.

    let observer;//监听器
    let timerID;//定时器

    //开始监听
    function startObserve(){
        //广告节点监听
        const targetNode = document.querySelector(`.video-ads.ytp-ad-module`);

        //这个视频不存在广告
        if(!targetNode){
            log(`这个视频不存在广告`);
            return false;
        }

        //监听视频中的广告并处理
        const config = {childList: true, subtree: true };// 监听目标节点本身与子树下节点的变动
        observer = new MutationObserver(skipAd);// 创建一个观察器实例并设置处理广告的回调函数
        observer.observe(targetNode, config);// 以上述配置开始观察广告节点

        timerID=setInterval(skipAd, 512);//漏网鱼

    }

    //结束监听
    function closeObserve(){
        observer.disconnect();
        observer = null;
        clearInterval(timerID);
    }

    //轮询任务
    setInterval(function(){
        //视频播放页
        if(getUrlParams(`v`)){
            if(observer){
                return false;
            }
            startObserve();
        }else{
            //其它界面
            if(!observer){
                return false;
            }
            closeObserve();
        }
    },16);

    log(`运行去除播放中的广告功能成功`)
}

/**
* main函数
*/
function main(){
    generateRemoveADHTMLElement(generateRemoveADCssText(cssSeletorArr));//移除界面中的广告.
    removePlayerAD();//移除播放中的广告.
}

if (document.readyState === `loading`) {
    log(`YouTube去广告脚本即将调用:`);
    document.addEventListener(`DOMContentLoaded`, main);// 此时加载尚未完成
} else {
    log(`YouTube去广告脚本快速调用:`);
    main();// 此时`DOMContentLoaded` 已经被触发
}

})();

@Guters
Copy link

Guters commented Oct 18, 2023

again a new update and it doesnt work anymore :(

@grant
Copy link

grant commented Oct 19, 2023

Stop @ mentioning me @PeterFuciik

@ka3ak169
Copy link

fixed it so that the video does not interrupt and so that you can use notifications

// ==UserScript==
// @name         youtube popup killer
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  try to take over the world!
// @author       Selbereth
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
  window.debug = true;
  if (debug) console.log("started");
  setInterval(() => {
    if (!!popupFind()) {
      if (debug) console.log("remove popup");
     const popup = popupFind()
     console.log(popup)
      popup.parentNode.removeChild(popup)

      if (debug) console.log("resume video");
      pauseFind().click()
      if (debug) console.log("done ");
    }
  }, 1000);
})();

function popupFind() {
  const targetPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
  const ignoredPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-iron-dropdown");

  if (ignoredPopup) {
      return null;
  }

  return targetPopup;
}

function pauseFind(){
  return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
}

@AntonioScrypt
Copy link

fixed it so that the video does not interrupt and so that you can use notifications

// ==UserScript==
// @name         youtube popup killer
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  try to take over the world!
// @author       Selbereth
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
  window.debug = true;
  if (debug) console.log("started");
  setInterval(() => {
    if (!!popupFind()) {
      if (debug) console.log("remove popup");
     const popup = popupFind()
     console.log(popup)
      popup.parentNode.removeChild(popup)

      if (debug) console.log("resume video");
      pauseFind().click()
      if (debug) console.log("done ");
    }
  }, 1000);
})();

function popupFind() {
  const targetPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
  const ignoredPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-iron-dropdown");

  if (ignoredPopup) {
      return null;
  }

  return targetPopup;
}

function pauseFind(){
  return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
}

its working for me ty sir

@jhoward39
Copy link

jhoward39 commented Oct 19, 2023

sorry, noob question: Are you only using tamper monkey? Any other options? Pros, Cons?

@ItsProfessional
Copy link

ItsProfessional commented Oct 19, 2023

sorry, noob question: Are you only using tamper monkey? Any other options? Pros, Cons?

Violentmonkey. For most people who just install a script and forget about it, it's equally as good.

@Eraze1102
Copy link

Eraze1102 commented Oct 19, 2023

fixed it so that the video does not interrupt and so that you can use notifications

// ==UserScript==
// @name         youtube popup killer
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  try to take over the world!
// @author       Selbereth
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
  window.debug = true;
  if (debug) console.log("started");
  setInterval(() => {
    if (!!popupFind()) {
      if (debug) console.log("remove popup");
     const popup = popupFind()
     console.log(popup)
      popup.parentNode.removeChild(popup)

      if (debug) console.log("resume video");
      pauseFind().click()
      if (debug) console.log("done ");
    }
  }, 1000);
})();

function popupFind() {
  const targetPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
  const ignoredPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-iron-dropdown");

  if (ignoredPopup) {
      return null;
  }

  return targetPopup;
}

function pauseFind(){
  return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
}

it does not work for me, can you explain ? i installed temeprmonkey, i clicked on the "+" to create a new script, i delete what is shown there, then copy 1to 1 what you have posted, then i save it so it is active, anything more to do ? it does not work, they still ask me to deactivate stuff, but i deactivated ALL adblcokers and pluggins...

@Eraze1102
Copy link

@ka3ak169

at 14,17,22,24 it says "debug is not defined"

@ka3ak169
Copy link

@Eraze1102
My friend, I'm not exactly a big professional in this matter. My knowledge is limited to some courses I've taken and the help from ChatGPT. It might be related to the browser you're using. I'm on Chrome. Try this code where the issue with "debug" has been fixed.

// ==UserScript==
// @name         youtube popup killer
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  try to take over the world!
// @author       Selbereth
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
  const debug = true;
  if (debug) console.log("started");
  setInterval(() => {
    try {
      if (!!popupFind()) {
        if (debug) console.log("remove popup");
        const popup = popupFind();
        console.log(popup);
        popup.parentNode.removeChild(popup);

        if (debug) console.log("resume video");
        pauseFind().click();
        if (debug) console.log("done ");
      }
    } catch (error) {
      console.error("Error in the interval:", error);
    }
  }, 1000);
})();

function popupFind() {
  const targetPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
  const ignoredPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-iron-dropdown");

  if (ignoredPopup) {
      return null; // не делаем ничего, если найден второй тип всплывающего окна
  }

  return targetPopup;
}

function pauseFind(){

  return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");

}

@Eraze1102
Copy link

@ALL

i found an easy script that works, follow the instructions in this Video !!!
https://www.youtube.com/watch?v=XMRr-1sm_XQ

REALLY SUPER EASY DISABLE ALL OTHER BLOCKERS THEREFORE

@vauxious
Copy link

can you exclude the share popup? because everytime i want to share the video, the popup didn't show

@ka3ak169
Copy link

@vauxious
Friend, I made it so the "share" pop-up wouldn't disappear, but I myself used the solution that was recommended by @Eraze1102
I found it to be simpler

// ==UserScript==
// @name         youtube popup killer
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  try to take over the world!
// @author       Selbereth
// @match        https://*.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function () {
  const debug = true;
  if (debug) console.log("started");
  setInterval(() => {
    try {
      if (!!popupFind()) {
        console.log('close addPopup');
        if (debug) console.log("remove popup");
        const popup = popupFind();
        console.log(popup);
        popup.parentNode.removeChild(popup);

        if (debug) console.log("resume video");
        pauseFind().click();
        if (debug) console.log("done ");
      }
    } catch (error) {
      console.error("Error in the interval:", error);
    }
  }, 1000);
})();

function popupFind() {
  const targetPopup = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");
  const ignoredPopup1 = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-iron-dropdown");
  const ignoredPopup2 = document.querySelector("body > ytd-app > ytd-popup-container > tp-yt-paper-dialog");  //sharePopup

  if (ignoredPopup1 || ignoredPopup2) {
      console.log('open ignoredPopup');
      return null;
  }
  return targetPopup;
}

function pauseFind(){
  return document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button");
}

@Eraze1102
Copy link

the solution in the Video still works, i dont know what yall mean by pop up ...

@ld79
Copy link

ld79 commented Oct 25, 2023

the solution in the Video still works, i dont know what yall mean by pop up ...

there is no vid my man, so share the secret knowledge if there is one

@ld79
Copy link

ld79 commented Oct 25, 2023

@H3mul
Copy link

H3mul commented Oct 26, 2023

Made slight adjustments to the OP submission that reacts to DOM changes directly instead of polling for popups every second (similar to @PeterFuciik's submission, uses the MutationObserver), please find here:

https://gist.github.com/H3mul/54145fbfafe89a03c2ce24fdcb66a868

@mjdaved
Copy link

mjdaved commented Nov 2, 2023

Hi, I have realized the scripts work when I use Tampermonkey in Google Chrome, but when I use Tampermonkey on Opera, it does not work as I have been an opera user for a long time. Can someone help me?

@mjdaved
Copy link

mjdaved commented Nov 2, 2023

Hi, I have realized the scripts work when I use Tampermonkey in Google Chrome, but when I use Tampermonkey on Opera, it does not work as I have been an opera user for a long time. Can someone help me?

Ok, I fixed the problem. I disabled adblock by opera and ADblock Plus and used uBlockOrigin and Tampermonkey instead. I still get side ads, but not in the video like before. If I use Opera adblock, YouTube doesn't just block you by popup; they completely block the video and make it impossible to watch.

@7modi-hue
Copy link

Can you help me with this link except ads

@7modi-hue
Copy link

@Pein1911
Copy link

Pein1911 commented Nov 8, 2023

Made slight adjustments to the OP submission that reacts to DOM changes directly instead of polling for popups every second (similar to @PeterFuciik's submission, uses the MutationObserver), please find here:

https://gist.github.com/H3mul/54145fbfafe89a03c2ce24fdcb66a868

It seems video pause everytime youtube show the popup and script run, can you fix it ?

@SpiritOfSuffering
Copy link

SpiritOfSuffering commented Nov 10, 2023

Все предложенные выше варианты больше не работают. Теперь YouTube блокирует видео проигрыватель после 3-ёх зафиксированных случаев, с использованием любого плагина напоминающего или являющемся блокировщиком рекламы. Если вы читаете это, знайте YouTube ничего не блокирует, это иллюзия. На самом деле, блокировка происходит со стороны браузера который вы используете.

Если вы хотите избежать блокировок, скачайте и используйте браузер - Vivaldi. Он основан на браузере Opera до 12 версии.

Используйте браузер - Firefox. Перед использованием, внимательно настройте вкладку настроек "Приватность и Защита". Вы всё ещё можете продолжать использовать uBlock Origin. Вот уже несколько недель я тестирую данный браузер и не испытаваю с ним проблем в отношении блокировок YouTube.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment