youtube去广告

简单高效的youtube去广告脚本,拒绝花里胡哨。如果你有一丢丢编程知识,可以尝试为常量cssSeletorArr定义元素。如果你有好的建议可以联系我zgh0118c@gmail.com。

当前为 2023-02-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name youtube去广告
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.31
  5. // @description 简单高效的youtube去广告脚本,拒绝花里胡哨。如果你有一丢丢编程知识,可以尝试为常量cssSeletorArr定义元素。如果你有好的建议可以联系我zgh0118c@gmail.com
  6. // @author FuckAD
  7. // @match https://www.youtube.com/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12. (function() {
  13. 'use strict';
  14.  
  15. //界面广告选择器
  16. const cssSeletorArr = [
  17. `#masthead-ad`,//首页顶部横幅广告
  18. `ytd-rich-item-renderer.style-scope.ytd-rich-grid-row:has(.ytd-display-ad-renderer)`,//首页视频排版广告
  19. `ytd-rich-section-renderer #dismissible`,//首页中部横幅广告
  20. `.video-ads.ytp-ad-module`,//播放器底部广告
  21. `tp-yt-paper-dialog:has(yt-mealbar-promo-renderer)`,//播放页会员促销广告
  22. `#related #player-ads`,//播放页评论区右侧推广广告
  23. `#related ytd-ad-slot-renderer`,//播放页评论区右侧视频排版广告
  24. ];
  25.  
  26. /**
  27. * 生成去除广告的css元素style并附加到HTML节点上
  28. * @param {String} styles 样式文本
  29. * @param {String} styleId 元素id
  30. * @return {undefined}
  31. */
  32. function generateRemoveAdHTMLElement(styles,styleId) {
  33. //如果已经设置过,退出
  34. if (document.getElementById(styleId)) {
  35. return false
  36. }
  37.  
  38. //设置移除广告样式
  39. let style = document.createElement(`style`);//创建style元素
  40. style.id = styleId;
  41. (document.querySelector(`head`) || document.querySelector(`body`)).appendChild(style);//将节点附加到HTML
  42. style.appendChild(document.createTextNode(styles));//附加样式节点到元素节点
  43. }
  44.  
  45. /**
  46. * 生成去除广告的css文本
  47. * @param {Array} cssSeletorArr 待设置css选择器数组
  48. * @return {String}
  49. */
  50. function generateRemoveAdCssText(cssSeletorArr){
  51. cssSeletorArr.forEach((seletor,index)=>{
  52. cssSeletorArr[index]=`${seletor}{display:none!important}`;//遍历并设置样式
  53. });
  54. return cssSeletorArr.join(" ");//拼接成字符串
  55. }
  56.  
  57. /**
  58. * 去除播放中的广告
  59. * @return {undefined}
  60. */
  61. function removePlayerAd(){
  62. let timerId =setInterval(function(){
  63. //拥有跳过按钮的广告
  64. let skipButton = document.querySelector(`.ytp-ad-skip-button`);
  65. if(skipButton)
  66. {
  67. skipButton.click();// 跳过广告
  68. return false;//防止后面错判
  69. }
  70.  
  71. //片头短广告
  72. let adShortMsg = document.querySelector(`.video-ads.ytp-ad-module .ytp-ad-player-overlay`);
  73. if(adShortMsg){
  74. location.href = location.href;//重新加载
  75. clearInterval(timerId);
  76. }
  77.  
  78. }, 16);//主流屏幕刷新率为60hz,此设置与16.666666毫秒每帧对应
  79. }
  80.  
  81. /**
  82. * main函数
  83. */
  84. function main(){
  85. generateRemoveAdHTMLElement(generateRemoveAdCssText(cssSeletorArr),`removeAd`);//移除界面中的广告
  86. removePlayerAd();//移除播放中的广告
  87. }
  88. main();
  89.  
  90. })();