YouTube去广告

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

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

  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.14
  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. setInterval(()=>{
  190. let video = document.querySelector('.ad-showing video') || document.querySelector('video');
  191. if(video.paused && video.currentTime<1){
  192. video.play();
  193. log("自动播放视频");
  194. }
  195. },16)
  196. }
  197.  
  198.  
  199. /**
  200. * 跳过广告
  201. * @return {undefined}
  202. */
  203. function skipAd(mutationsList, observer) {
  204. let video = document.querySelector(`.ad-showing video`) || document.querySelector(`video`);//获取视频节点
  205. let skipButton = document.querySelector(`.ytp-ad-skip-button`) || document.querySelector(`.ytp-skip-ad-button`) || document.querySelector(`.ytp-ad-skip-button-modern`);
  206. let shortAdMsg = document.querySelector(`.video-ads.ytp-ad-module .ytp-ad-player-overlay`) || document.querySelector(`.ytp-ad-button-icon`);
  207.  
  208. //移除YT拦截广告拦截弹窗
  209. const premiumContainers = [...document.querySelectorAll(`ytd-popup-container`)];
  210. const matchingContainers = premiumContainers.filter(container => container.querySelector(`a[href="/premium"]`));
  211.  
  212. if(matchingContainers.length>0){
  213. matchingContainers.forEach(container => container.remove());
  214. log(`移除YT拦截器`);
  215. }
  216.  
  217. // 获取所有具有指定标签的元素
  218. const backdrops = document.querySelectorAll('tp-yt-iron-overlay-backdrop');
  219. // 查找具有特定样式的元素
  220. const targetBackdrop = Array.from(backdrops).find(
  221. (backdrop) => backdrop.style.zIndex === '2201'
  222. );
  223. // 如果找到该元素,清空其类并移除 open 属性
  224. if (targetBackdrop) {
  225. targetBackdrop.className = ''; // 清空所有类
  226. targetBackdrop.removeAttribute('opened'); // 移除 open 属性
  227. log(`关闭遮罩层`);
  228. }
  229.  
  230.  
  231. if((skipButton || shortAdMsg) && window.location.href.indexOf("https://m.youtube.com/") === -1){ //移动端静音有bug
  232. video.muted = true;
  233. //video.playbackRate = 16;
  234. //video.play();
  235. //log(`调速~~~~~~~~~~~~~`);
  236. }
  237.  
  238. if(skipButton){
  239. if(video.currentTime>0.5){
  240. video.currentTime = video.duration;//强制
  241. log(`特殊账号跳过按钮广告~~~~~~~~~~~~~`);
  242. return;
  243. }
  244. skipButton.click();//PC
  245. nativeTouch.call(skipButton);//Phone
  246. log(`按钮跳过广告~~~~~~~~~~~~~`);
  247. }else if(shortAdMsg && video.currentTime>0.5){
  248. video.currentTime = video.duration;//强制
  249. log(`强制结束了该广告`);
  250. }
  251.  
  252. }
  253.  
  254. /**
  255. * 去除播放中的广告
  256. * @return {undefined}
  257. */
  258. function removePlayerAD(id){
  259. //如果已经在运行,退出.
  260. if (checkRunFlag(id)) {
  261. log(`去除播放中的广告功能已在运行`);
  262. return false
  263. }
  264. let observer;//监听器
  265. let timerID;//定时器
  266.  
  267. //开始监听
  268. function startObserve(){
  269. //广告节点监听
  270. const targetNode = document.querySelector(`.video-ads.ytp-ad-module`);
  271. if(!targetNode){
  272. log(`正在寻找待监听的目标节点`);
  273. return false;
  274. }
  275. //监听视频中的广告并处理
  276. const config = {childList: true, subtree: true };// 监听目标节点本身与子树下节点的变动
  277. observer = new MutationObserver(skipAd);// 创建一个观察器实例并设置处理广告的回调函数
  278. observer.observe(targetNode, config);// 以上述配置开始观察广告节点
  279. timerID=setInterval(skipAd, 16);//漏网鱼
  280. }
  281.  
  282. //轮询任务
  283. let startObserveID = setInterval(()=>{
  284. if(observer && timerID){
  285. clearInterval(startObserveID);
  286. }else{
  287. startObserve();
  288. }
  289. },16);
  290.  
  291. log(`运行去除播放中的广告功能成功`);
  292. }
  293.  
  294. /**
  295. * main函数
  296. */
  297. function main(){
  298. generateRemoveADHTMLElement(`removeADHTMLElement`);//移除界面中的广告.
  299. removePlayerAD(`removePlayerAD`);//移除播放中的广告.
  300. autoPlayAfterAd();//自动播放被暂停的视频
  301. }
  302.  
  303. if (document.readyState === `loading`) {
  304. log(`YouTube去广告脚本即将调用:`);
  305. document.addEventListener(`DOMContentLoaded`, main);// 此时加载尚未完成
  306. } else {
  307. log(`YouTube去广告脚本快速调用:`);
  308. main();// 此时`DOMContentLoaded` 已经被触发
  309. }
  310.  
  311. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址