mute-youtube-ad

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

content.js (1622B)


      1 // ミュート制御の本体
      2 const applyMuteLogic = () => {
      3   const video = document.querySelector('video');
      4   const player = document.querySelector('#movie_player');
      5   
      6   if (!video || !player) return;
      7 
      8   // 広告中かどうかを判定する複数のフラグ
      9   // 1. YouTube公式のプレイヤーが持つクラス
     10   // 2. 「広告詳細」ボタンの存在
     11   // 3. 「スキップ」関連の要素の出現
     12   const isAd = player.classList.contains('ad-showing') || 
     13                player.classList.contains('ad-interrupting') ||
     14                document.querySelector('.ytp-ad-player-overlay') !== null;
     15 
     16   if (isAd) {
     17     if (!video.muted) {
     18       console.log("[Ad Muter] 広告を検知: ミュートします");
     19       video.muted = true;
     20     }
     21   } else {
     22     if (video.muted) {
     23       // 広告が終わった瞬間にミュート解除
     24       console.log("[Ad Muter] 広告終了: ミュートを解除します");
     25       video.muted = false;
     26     }
     27   }
     28 };
     29 
     30 // 監視の設定
     31 // 属性の変化(クラス名の追加など)と、子要素(広告オーバーレイ)の追加を監視
     32 const observer = new MutationObserver((mutations) => {
     33   applyMuteLogic();
     34 });
     35 
     36 // YouTubeのメインプレイヤー要素をターゲットにする(bodyより効率的)
     37 const target = document.body;
     38 observer.observe(target, {
     39   childList: true,
     40   subtree: true,
     41   attributes: true,
     42   attributeFilter: ['class']
     43 });
     44 
     45 // ページ遷移(SPA対策)時にも対応できるよう、定期的な生存確認も念のため入れる
     46 setInterval(applyMuteLogic, 500);