エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Enhancer for YouTubeでミニプレイヤーで動画を見ながらタイムスタンプをクリックしたときに勝手にスクロールされなくする

Last updated at Posted at 2024-11-27

はじめに

拡張機能Enhancer for YouTubeを導入すると、Youtubeがめっちゃ便利になります。
この機能の一つにミニプレイヤーというものがあり、下にスクロールすると動画が固定位置で再生されるので、動画を見ながらコメントや関連動画を確認できます。

image.png

しかし、タイムスタンプをクリックすると勝手に一番上までスクロールされます。
コメント欄の続きを確認したいときに、下まで再度スクロールする必要があり、大変不便。
この挙動を回避すべく調べたところ、シンプルな解決方法を見つけたので備忘録として残します。

解決方法

  1. Enhancer for YouTubeの設定画面を開き、カスタムスクリプトに以下のコードを貼り付けて保存
  2. 「YouTubeがタブに読み込まれたときに自動的にスクリプトを実行する」のチェックボックスを有効化
document.addEventListener('click', (event) => {
    // クリックされた要素がリンクであるか確認
    const target = event.target;
    if (target.tagName !== 'A') return;

    // YouTubeのリンクであるか確認
    const isYouTubeLink = target.href.includes('youtube.com/watch');
    if (!isYouTubeLink) return;

    // 同じ動画かどうかを確認
    const currentVideoId = new URL(window.location.href).searchParams.get('v');
    const targetVideoId = new URL(target.href).searchParams.get('v');
    if (currentVideoId !== targetVideoId) return;

    // タイムスタンプが含まれているか確認
    const hasTimestamp = new URL(target.href).searchParams.has('t');
    if (!hasTimestamp) return;

    event.preventDefault();  // デフォルトのリンク動作を無効化
    event.stopPropagation(); // イベントのバブリングを停止

    // 動画要素を取得
    const videoElement = document.querySelector('video');
    if (!videoElement) return;

    // タイムスタンプを取得
    const timestamp = new URL(target.href).searchParams.get('t');
    if (!timestamp) return;

    // 非数値文字を取り除いて数値に変換
    const timeInSeconds = parseFloat(timestamp.replace(/[^\d]/g, ''));
    if (isNaN(timeInSeconds)) return;

    // 動画の再生位置を設定して再生
    videoElement.currentTime = timeInSeconds;
    videoElement.play();
}, true);

これにより、タイムスタンプをクリックしても勝手にスクロールされなくなります。

1
0
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?