YouTube去广告

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

目前为 2023-12-14 提交的版本。查看 最新版本

  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.01
  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. //界面广告选择器
  27. const cssSeletorArr = [
  28. `#masthead-ad`,//首页顶部横幅广告.
  29. `ytd-rich-item-renderer.style-scope.ytd-rich-grid-row #content:has(.ytd-display-ad-renderer)`,//首页视频排版广告.
  30. `.video-ads.ytp-ad-module`,//播放器底部广告.
  31. `tp-yt-paper-dialog:has(yt-mealbar-promo-renderer)`,//播放页会员促销广告.
  32. `ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-ads"]`,//播放页右上方推荐广告.
  33. `#related #player-ads`,//播放页评论区右侧推广广告.
  34. `#related ytd-ad-slot-renderer`,//播放页评论区右侧视频排版广告.
  35. `ytd-ad-slot-renderer`,//搜索页广告.
  36. `yt-mealbar-promo-renderer`,//播放页会员推荐广告.
  37. `ad-slot-renderer`,//M播放页第三方推荐广告
  38. `ytm-companion-ad-renderer`,//M可跳过的视频广告链接处
  39. ];
  40.  
  41. window.dev=false;//开发使用
  42.  
  43. /**
  44. * 将标准时间格式化
  45. * @param {Date} time 标准时间
  46. * @param {String} format 格式
  47. * @return {String}
  48. */
  49. function moment(time) {
  50. // 获取年⽉⽇时分秒
  51. let y = time.getFullYear()
  52. let m = (time.getMonth() + 1).toString().padStart(2, `0`)
  53. let d = time.getDate().toString().padStart(2, `0`)
  54. let h = time.getHours().toString().padStart(2, `0`)
  55. let min = time.getMinutes().toString().padStart(2, `0`)
  56. let s = time.getSeconds().toString().padStart(2, `0`)
  57. return `${y}-${m}-${d} ${h}:${min}:${s}`
  58. }
  59.  
  60. /**
  61. * 输出信息
  62. * @param {String} msg 信息
  63. * @return {undefined}
  64. */
  65. function log(msg) {
  66. if(!window.dev){
  67. return false;
  68. }
  69. console.log(window.location.href);
  70. console.log(`${moment(new Date())} ${msg}`);
  71. }
  72.  
  73. /**
  74. * 设置运行标志
  75. * @param {String} name
  76. * @return {undefined}
  77. */
  78. function setRunFlag(name){
  79. let style = document.createElement(`style`);
  80. style.id = name;
  81. (document.querySelector(`head`) || document.querySelector(`body`)).appendChild(style);//将节点附加到HTML.
  82. }
  83.  
  84. /**
  85. * 获取运行标志
  86. * @param {String} name
  87. * @return {undefined|Element}
  88. */
  89. function getRunFlag(name){
  90. return document.getElementById(name);
  91. }
  92.  
  93. /**
  94. * 检查是否设置了运行标志
  95. * @param {String} name
  96. * @return {Boolean}
  97. */
  98. function checkRunFlag(name){
  99. if(getRunFlag(name)){
  100. return true;
  101. }else{
  102. setRunFlag(name)
  103. return false;
  104. }
  105. }
  106.  
  107. /**
  108. * 生成去除广告的css元素style并附加到HTML节点上
  109. * @param {String} styles 样式文本
  110. * @return {undefined}
  111. */
  112. function generateRemoveADHTMLElement(id) {
  113. //如果已经设置过,退出.
  114. if (checkRunFlag(id)) {
  115. log(`屏蔽页面广告节点已生成`);
  116. return false
  117. }
  118.  
  119. //设置移除广告样式.
  120. let style = document.createElement(`style`);//创建style元素.
  121. (document.querySelector(`head`) || document.querySelector(`body`)).appendChild(style);//将节点附加到HTML.
  122. style.appendChild(document.createTextNode(generateRemoveADCssText(cssSeletorArr)));//附加样式节点到元素节点.
  123. log(`生成屏蔽页面广告节点成功`);
  124. }
  125.  
  126. /**
  127. * 生成去除广告的css文本
  128. * @param {Array} cssSeletorArr 待设置css选择器数组
  129. * @return {String}
  130. */
  131. function generateRemoveADCssText(cssSeletorArr){
  132. cssSeletorArr.forEach((seletor,index)=>{
  133. cssSeletorArr[index]=`${seletor}{display:none!important}`;//遍历并设置样式.
  134. });
  135. return cssSeletorArr.join(` `);//拼接成字符串.
  136. }
  137.  
  138. /**
  139. * 触摸事件
  140. * @return {undefined}
  141. */
  142. function nativeTouch(){
  143. // 创建 Touch 对象
  144. let touch = new Touch({
  145. identifier: Date.now(),
  146. target: this,
  147. clientX: 12,
  148. clientY: 34,
  149. radiusX: 56,
  150. radiusY: 78,
  151. rotationAngle: 0,
  152. force: 1
  153. });
  154.  
  155. // 创建 TouchEvent 对象
  156. let touchStartEvent = new TouchEvent(`touchstart`, {
  157. bubbles: true,
  158. cancelable: true,
  159. view: window,
  160. touches: [touch],
  161. targetTouches: [touch],
  162. changedTouches: [touch]
  163. });
  164.  
  165. // 分派 touchstart 事件到目标元素
  166. this.dispatchEvent(touchStartEvent);
  167.  
  168. // 创建 TouchEvent 对象
  169. let touchEndEvent = new TouchEvent(`touchend`, {
  170. bubbles: true,
  171. cancelable: true,
  172. view: window,
  173. touches: [],
  174. targetTouches: [],
  175. changedTouches: [touch]
  176. });
  177.  
  178. // 分派 touchend 事件到目标元素
  179. this.dispatchEvent(touchEndEvent);
  180. }
  181.  
  182. /**
  183. * 跳过广告
  184. * @return {undefined}
  185. */
  186. function skipAd(mutationsList, observer) {
  187. let video = document.querySelector(`.ad-showing video`) || document.querySelector(`video`);//获取视频节点
  188. let skipButton = document.querySelector(`.ytp-ad-skip-button`) || document.querySelector(`.ytp-ad-skip-button-modern`);
  189. let shortAdMsg = document.querySelector(`.video-ads.ytp-ad-module .ytp-ad-player-overlay`);
  190.  
  191. if(skipButton){
  192. //移动端静音有bug
  193. if( window.location.href.indexOf("https://m.youtube.com/") === -1){
  194. video.muted = true;
  195. }
  196. if(video.currentTime>0.5){
  197. video.currentTime = video.duration;//强制
  198. log(`特殊账号跳过按钮广告~~~~~~~~~~~~~`);
  199. return;
  200. }
  201. skipButton.click();//PC
  202. nativeTouch.call(skipButton);//Phone
  203. log(`按钮跳过广告~~~~~~~~~~~~~`);
  204. }else if(shortAdMsg){
  205. video.currentTime = video.duration;
  206. log(`强制结束了该广告~~~~~~~~~~~~~`);
  207. }else{
  208. log(`######广告不存在######`);
  209. }
  210.  
  211. }
  212.  
  213. /**
  214. * 去除播放中的广告
  215. * @return {undefined}
  216. */
  217. function removePlayerAD(id){
  218. //如果已经在运行,退出.
  219. if (checkRunFlag(id)) {
  220. log(`去除播放中的广告功能已在运行`);
  221. return false
  222. }
  223. let observer;//监听器
  224. let timerID;//定时器
  225.  
  226. //开始监听
  227. function startObserve(){
  228. //广告节点监听
  229. const targetNode = document.querySelector(`.video-ads.ytp-ad-module`);
  230. if(!targetNode){
  231. log(`正在寻找待监听的目标节点`);
  232. return false;
  233. }
  234. //监听视频中的广告并处理
  235. const config = {childList: true, subtree: true };// 监听目标节点本身与子树下节点的变动
  236. observer = new MutationObserver(skipAd);// 创建一个观察器实例并设置处理广告的回调函数
  237. observer.observe(targetNode, config);// 以上述配置开始观察广告节点
  238. timerID=setInterval(skipAd, 500);//漏网鱼
  239. }
  240.  
  241. //轮询任务
  242. let startObserveID = setInterval(()=>{
  243. if(observer && timerID){
  244. clearInterval(startObserveID);
  245. }else{
  246. startObserve();
  247. }
  248. },16);
  249.  
  250. log(`运行去除播放中的广告功能成功`);
  251. }
  252.  
  253. /**
  254. * main函数
  255. */
  256. function main(){
  257. generateRemoveADHTMLElement(`removeADHTMLElement`);//移除界面中的广告.
  258. removePlayerAD(`removePlayerAD`);//移除播放中的广告.
  259. }
  260.  
  261. if (document.readyState === `loading`) {
  262. log(`YouTube去广告脚本即将调用:`);
  263. document.addEventListener(`DOMContentLoaded`, main);// 此时加载尚未完成
  264. } else {
  265. log(`YouTube去广告脚本快速调用:`);
  266. main();// 此时`DOMContentLoaded` 已经被触发
  267. }
  268.  
  269. })();