YouTube去广告

这是一个去除YouTube广告的脚本,轻量且高效,它能丝滑的去除界面广告和视频广告,包括6s广告。

当前为 2024-07-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube去广告 YouTube AD Blocker
  3. // @name:zh-CN YouTube去广告
  4. // @name:zh-TW YouTube去廣告
  5. // @name:zh-HK YouTube去廣告
  6. // @name:zh-MO YouTube去廣告
  7. // @namespace https://github.com/iamfugui/YouTubeADB
  8. // @version 6.13
  9. // @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.
  10. // @description:zh-CN 这是一个去除YouTube广告的脚本,轻量且高效,它能丝滑的去除界面广告和视频广告,包括6s广告。
  11. // @description:zh-TW 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
  12. // @description:zh-HK 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
  13. // @description:zh-MO 這是一個去除YouTube廣告的腳本,輕量且高效,它能絲滑地去除界面廣告和視頻廣告,包括6s廣告。
  14. // @author iamfugui
  15. // @match *://*.youtube.com/*
  16. // @exclude *://accounts.youtube.com/*
  17. // @exclude *://www.youtube.com/live_chat_replay*
  18. // @exclude *://www.youtube.com/persist_identity*
  19. // @icon https://www.google.com/s2/favicons?sz=64&domain=YouTube.com
  20. // @grant none
  21. // @license MIT
  22. // ==/UserScript==
  23. (function() {
  24. `use strict`;
  25. //界面广告选择器
  26. const cssSelectorArr = [
  27. `#masthead-ad`,//首页顶部横幅广告.
  28. `ytd-rich-item-renderer.style-scope.ytd-rich-grid-row #content:has(.ytd-display-ad-renderer)`,//首页视频排版广告.
  29. `.video-ads.ytp-ad-module`,//播放器底部广告.
  30. `tp-yt-paper-dialog:has(yt-mealbar-promo-renderer)`,//播放页会员促销广告.
  31. `ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-ads"]`,//播放页右上方推荐广告.
  32. `#related #player-ads`,//播放页评论区右侧推广广告.
  33. `#related ytd-ad-slot-renderer`,//播放页评论区右侧视频排版广告.
  34. `ytd-ad-slot-renderer`,//搜索页广告.
  35. `yt-mealbar-promo-renderer`,//播放页会员推荐广告.
  36. //`tp-yt-iron-overlay-backdrop[style*="z-index: 2201;"]`,//会员拦截广告
  37. `ytd-popup-container:has(a[href="/premium"])`,//会员拦截广告
  38. `ad-slot-renderer`,//M播放页第三方推荐广告
  39. `ytm-companion-ad-renderer`,//M可跳过的视频广告链接处
  40. ];
  41.  
  42. window.dev=false;//开发使用
  43.  
  44. /**
  45. * 将标准时间格式化
  46. * @param {Date} time 标准时间
  47. * @param {String} format 格式
  48. * @return {String}
  49. */
  50. function moment(time) {
  51. // 获取年⽉⽇时分秒
  52. let y = time.getFullYear()
  53. let m = (time.getMonth() + 1).toString().padStart(2, `0`)
  54. let d = time.getDate().toString().padStart(2, `0`)
  55. let h = time.getHours().toString().padStart(2, `0`)
  56. let min = time.getMinutes().toString().padStart(2, `0`)
  57. let s = time.getSeconds().toString().padStart(2, `0`)
  58. return `${y}-${m}-${d} ${h}:${min}:${s}`
  59. }
  60.  
  61. /**
  62. * 输出信息
  63. * @param {String} msg 信息
  64. * @return {undefined}
  65. */
  66. function log(msg) {
  67. if(!window.dev){
  68. return false;
  69. }
  70. console.log(window.location.href);
  71. console.log(`${moment(new Date())} ${msg}`);
  72. }
  73.  
  74. /**
  75. * 设置运行标志
  76. * @param {String} name
  77. * @return {undefined}
  78. */
  79. function setRunFlag(name){
  80. let style = document.createElement(`style`);
  81. style.id = name;
  82. (document.head || document.body).appendChild(style);//将节点附加到HTML.
  83. }
  84.  
  85. /**
  86. * 获取运行标志
  87. * @param {String} name
  88. * @return {undefined|Element}
  89. */
  90. function getRunFlag(name){
  91. return document.getElementById(name);
  92. }
  93.  
  94. /**
  95. * 检查是否设置了运行标志
  96. * @param {String} name
  97. * @return {Boolean}
  98. */
  99. function checkRunFlag(name){
  100. if(getRunFlag(name)){
  101. return true;
  102. }else{
  103. setRunFlag(name)
  104. return false;
  105. }
  106. }
  107.  
  108. /**
  109. * 生成去除广告的css元素style并附加到HTML节点上
  110. * @param {String} styles 样式文本
  111. * @return {undefined}
  112. */
  113. function generateRemoveADHTMLElement(id) {
  114. //如果已经设置过,退出.
  115. if (checkRunFlag(id)) {
  116. log(`屏蔽页面广告节点已生成`);
  117. return false
  118. }
  119.  
  120. //设置移除广告样式.
  121. let style = document.createElement(`style`);//创建style元素.
  122. (document.head || document.body).appendChild(style);//将节点附加到HTML.
  123. style.appendChild(document.createTextNode(generateRemoveADCssText(cssSelectorArr)));//附加样式节点到元素节点.
  124. log(`生成屏蔽页面广告节点成功`);
  125. }
  126.  
  127. /**
  128. * 生成去除广告的css文本
  129. * @param {Array} cssSelectorArr 待设置css选择器数组
  130. * @return {String}
  131. */
  132. function generateRemoveADCssText(cssSelectorArr){
  133. cssSelectorArr.forEach((selector,index)=>{
  134. cssSelectorArr[index]=`${selector}{display:none!important}`;//遍历并设置样式.
  135. });
  136. return cssSelectorArr.join(` `);//拼接成字符串.
  137. }
  138.  
  139. /**
  140. * 触摸事件
  141. * @return {undefined}
  142. */
  143. function nativeTouch(){
  144. // 创建 Touch 对象
  145. let touch = new Touch({
  146. identifier: Date.now(),
  147. target: this,
  148. clientX: 12,
  149. clientY: 34,
  150. radiusX: 56,
  151. radiusY: 78,
  152. rotationAngle: 0,
  153. force: 1
  154. });
  155.  
  156. // 创建 TouchEvent 对象
  157. let touchStartEvent = new TouchEvent(`touchstart`, {
  158. bubbles: true,
  159. cancelable: true,
  160. view: window,
  161. touches: [touch],
  162. targetTouches: [touch],
  163. changedTouches: [touch]
  164. });
  165.  
  166. // 分派 touchstart 事件到目标元素
  167. this.dispatchEvent(touchStartEvent);
  168.  
  169. // 创建 TouchEvent 对象
  170. let touchEndEvent = new TouchEvent(`touchend`, {
  171. bubbles: true,
  172. cancelable: true,
  173. view: window,
  174. touches: [],
  175. targetTouches: [],
  176. changedTouches: [touch]
  177. });
  178.  
  179. // 分派 touchend 事件到目标元素
  180. this.dispatchEvent(touchEndEvent);
  181. }
  182.  
  183.  
  184. /**
  185. * 自动播放
  186. * @return {undefined}
  187. */
  188. function autoPlayAfterAd(){
  189. let getDOMID = setInterval(()=>{
  190. let video = document.querySelector('.ad-showing video') || document.querySelector('video');
  191. log("寻找视频DOM")
  192.  
  193. if(video){
  194.  
  195. clearInterval(getDOMID);//直到找到视频DOM
  196.  
  197. setInterval(()=>{
  198. if(video.paused && video.currentTime<1){
  199. video.play();
  200. log("自动播放视频");
  201. }
  202. },16)
  203.  
  204. }
  205.  
  206. },16)
  207.  
  208. }
  209.  
  210.  
  211. /**
  212. * 跳过广告
  213. * @return {undefined}
  214. */
  215. function skipAd(mutationsList, observer) {
  216. let video = document.querySelector(`.ad-showing video`) || document.querySelector(`video`);//获取视频节点
  217. let skipButton = document.querySelector(`.ytp-ad-skip-button`) || document.querySelector(`.ytp-skip-ad-button`) || document.querySelector(`.ytp-ad-skip-button-modern`);
  218. let shortAdMsg = document.querySelector(`.video-ads.ytp-ad-module .ytp-ad-player-overlay`) || document.querySelector(`.ytp-ad-button-icon`);
  219.  
  220. //移除YT拦截广告拦截弹窗
  221. const premiumContainers = [...document.querySelectorAll(`ytd-popup-container`)];
  222. const matchingContainers = premiumContainers.filter(container => container.querySelector(`a[href="/premium"]`));
  223.  
  224. if(matchingContainers.length>0){
  225. matchingContainers.forEach(container => container.remove());
  226. log(`移除YT拦截器`);
  227. }
  228.  
  229. // 获取所有具有指定标签的元素
  230. const backdrops = document.querySelectorAll('tp-yt-iron-overlay-backdrop');
  231. // 查找具有特定样式的元素
  232. const targetBackdrop = Array.from(backdrops).find(
  233. (backdrop) => backdrop.style.zIndex === '2201'
  234. );
  235. // 如果找到该元素,清空其类并移除 open 属性
  236. if (targetBackdrop) {
  237. targetBackdrop.className = ''; // 清空所有类
  238. targetBackdrop.removeAttribute('opened'); // 移除 open 属性
  239. log(`关闭遮罩层`);
  240. }
  241.  
  242.  
  243. if((skipButton || shortAdMsg) && window.location.href.indexOf("https://m.youtube.com/") === -1){ //移动端静音有bug
  244. video.muted = true;
  245. //video.playbackRate = 16;
  246. //video.play();
  247. //log(`调速~~~~~~~~~~~~~`);
  248. }
  249.  
  250. if(skipButton){
  251. if(video.currentTime>0.5){
  252. video.currentTime = video.duration;//强制
  253. log(`特殊账号跳过按钮广告~~~~~~~~~~~~~`);
  254. return;
  255. }
  256. skipButton.click();//PC
  257. nativeTouch.call(skipButton);//Phone
  258. log(`按钮跳过广告~~~~~~~~~~~~~`);
  259. }else if(shortAdMsg && video.currentTime>0.5){
  260. video.currentTime = video.duration;//强制
  261. log(`强制结束了该广告`);
  262. }
  263.  
  264. }
  265.  
  266. /**
  267. * 去除播放中的广告
  268. * @return {undefined}
  269. */
  270. function removePlayerAD(id){
  271. //如果已经在运行,退出.
  272. if (checkRunFlag(id)) {
  273. log(`去除播放中的广告功能已在运行`);
  274. return false
  275. }
  276. let observer;//监听器
  277. let timerID;//定时器
  278.  
  279. //开始监听
  280. function startObserve(){
  281. //广告节点监听
  282. const targetNode = document.querySelector(`.video-ads.ytp-ad-module`);
  283. if(!targetNode){
  284. log(`正在寻找待监听的目标节点`);
  285. return false;
  286. }
  287. //监听视频中的广告并处理
  288. const config = {childList: true, subtree: true };// 监听目标节点本身与子树下节点的变动
  289. observer = new MutationObserver(skipAd);// 创建一个观察器实例并设置处理广告的回调函数
  290. observer.observe(targetNode, config);// 以上述配置开始观察广告节点
  291. timerID=setInterval(skipAd, 16);//漏网鱼
  292. }
  293.  
  294. //轮询任务
  295. let startObserveID = setInterval(()=>{
  296. if(observer && timerID){
  297. clearInterval(startObserveID);
  298. }else{
  299. startObserve();
  300. }
  301. },16);
  302.  
  303. log(`运行去除播放中的广告功能成功`);
  304. }
  305.  
  306. /**
  307. * main函数
  308. */
  309. function main(){
  310. generateRemoveADHTMLElement(`removeADHTMLElement`);//移除界面中的广告.
  311. removePlayerAD(`removePlayerAD`);//移除播放中的广告.
  312. autoPlayAfterAd();//自动播放被暂停的视频
  313. }
  314.  
  315. if (document.readyState === `loading`) {
  316. log(`YouTube去广告脚本即将调用:`);
  317. document.addEventListener(`DOMContentLoaded`, main);// 此时加载尚未完成
  318. } else {
  319. log(`YouTube去广告脚本快速调用:`);
  320. main();// 此时`DOMContentLoaded` 已经被触发
  321. }
  322.  
  323. })();