LoginSignup
1
1

Youtubeのチャンネルトップで自動再生されるビデオを止めるだけのchrome拡張

Posted at

毎回止めるの面倒

タイトルの通りです。お粗末な出来ですが折角ですので公開します。
(間違ってたらすみません)YoutubeはSPA(Single Page Application)が実装されているらしくページを移動しても再読み込みするまでcontent.jsが反応しないのでbackground.jsでurlの遷移を検知してそれを基にcontent.jsを動かしてます。

コード

manifest.json
{
    "name": "youtubeチャンネルページ動画ストッパー",
    "description": "チャンネルページのトップで自動再生される動画を停止します",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
      "service_worker": "background.js"
    },
    "content_scripts": [
        {
          "js": ["content.js"],
          "run_at": "document_end",
          "matches": ["https://www.youtube.com/*"]
        }
    ],
    "permissions": [
      "tabs"
    ]
}

background.js
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
  if(changeInfo.url !== void 0){
    if(changeInfo.url.indexOf("https://www.youtube.com/channel") === 0 || changeInfo.url.indexOf("https://www.youtube.com/@") === 0){
      chrome.tabs.query({active:true, currentWindow:true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id,changeInfo.url,function(response){
        });
      });
    }
  }
});

content.js
const observer = new MutationObserver(callback);
const config = {
    childList: true,
    subtree: true
};

function callback(mutations){
    if(document.querySelector("ytd-channel-video-player-renderer .html5-video-container > video") != null){
        video = document.querySelector("ytd-channel-video-player-renderer .html5-video-container > video");
        video.addEventListener("canplay",function(){
        	video.pause();
      	})
        observer.disconnect();
    }
}

url = window.location.href;
if(url.indexOf("https://www.youtube.com/channel") === 0 || url.indexOf("https://www.youtube.com/@") === 0){
  	observer.observe(document.body, config);
}

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
    observer.observe(document.body, config);
    sendResponse();
});

終わりに

chrome拡張は私のようなプログラミング初心者でも動いて実際に役に立つ(?)ものが簡単に作れるので同じく初心者の方に是非おすすめしたいです。
そのうちchrome拡張の作り方と頻繁に使うAPI等まとめて記事にするつもりです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1