日本語

“React: Adding and Switching WebVTT Subtitles on a Video”

​​React​Playwright,TypeScript,WebVTT

If you attach a WebVTT file to a <video> with a <track> element, the browser can display the subtitles over the video. Without a default attribute, nothing is shown at first. To choose which subtitles appear, set each subtitle's mode in video.textTracks to showing or disabled. In React, keep the selected language in state and apply it to mode in a useEffect.

Here we build a component that switches between Japanese, English, and off with a <select>. We also cover how to update the <select> when the subtitles change from outside it, how to display subtitles yourself outside the video, and what to check when subtitles don't appear, with the test results.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and headless Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0. The video was a 12-second test file (VP9 WebM) made with ffmpeg, and the test server also ran in this environment. I did not test Firefox, Safari, or smartphone browsers. I did not test switching from the browser's built-in subtitle menu; instead, I checked by changing mode from code.

During playback, changing the subtitle select from off to Japanese shows "The cat is looking out the window" over the bottom of the video. Changing it to English then shows "A bird has flown in." A label in the bottom-right corner, written in Japanese, shows the switch count as the 1st of 2 switches.
Switching subtitles from off to Japanese to English during playback. The cursor, the count display, and the pink frame were added over the recording for the GIF. The on-screen labels are in Japanese.

The WebVTT subtitle file

A subtitle file starts with WEBVTT. After that, pairs of a display time and a subtitle line are listed, separated by blank lines. The Japanese subtitles used in the test are shown below. The English subtitles (en.vtt) use the same times with English text.

text
WEBVTT

00:00:01.000 --> 00:00:04.000
猫が窓の外を見ています

00:00:05.000 --> 00:00:08.000
鳥が飛んできました

00:00:09.000 --> 00:00:11.500
猫はしっぽを振っています

According to the MDN description of the WebVTT format, the character encoding is UTF-8 and the MIME type is text/vtt. What happens when the leading WEBVTT is missing is covered in the section "What to check when subtitles don't appear" below.

Listing track elements and switching mode with a select

SubtitledVideo takes a video URL and a list of subtitles, and renders one <track> per subtitle. In JSX, write the HTML srclang attribute as srcLang.

tsx
import { useEffect, useRef, useState } from 'react';

export type Subtitle = { srcLang: string; label: string; src: string };

type Props = { src: string; subtitles: Subtitle[]; crossOrigin?: 'anonymous' };

// Subtitle language (srcLang), or 'off' for no subtitles
type Lang = string;

export function SubtitledVideo({ src, subtitles, crossOrigin }: Props) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [lang, setLang] = useState<Lang>('off');

  // Set only the subtitle for the selected language to showing; set the others to disabled
  useEffect(() => {
    const tracks = videoRef.current!.textTracks;
    for (const track of Array.from(tracks)) {
      track.mode = track.language === lang ? 'showing' : 'disabled';
    }
  }, [lang, subtitles]);

  // If mode changes elsewhere (e.g. the browser's subtitle menu), sync the selection
  useEffect(() => {
    const tracks = videoRef.current!.textTracks;
    const onChange = () => {
      const showing = Array.from(tracks)
        .filter((t) => t.mode === 'showing')
        .map((t) => t.language);
      // Prefer a track that has just become showing. If none is showing, use 'off'
      setLang((prev) => showing.find((l) => l !== prev) ?? (showing.length > 0 ? prev : 'off'));
    };
    tracks.addEventListener('change', onChange);
    return () => tracks.removeEventListener('change', onChange);
  }, []);

  return (
    <div>
      <video ref={videoRef} src={src} controls crossOrigin={crossOrigin} width={640}>
        {subtitles.map((s) => (
          <track key={s.src} kind="subtitles" src={s.src} srcLang={s.srcLang} label={s.label} />
        ))}
      </video>
      <label>
        字幕
        <select value={lang} onChange={(e) => setLang(e.target.value)}>
          <option value="off">オフ</option>
          {subtitles.map((s) => (
            <option key={s.srcLang} value={s.srcLang}>{s.label}</option>
          ))}
        </select>
      </label>
    </div>
  );
}

The caller passes something like subtitles={[{ srcLang: 'ja', label: '日本語', src: '/ja.vtt' }, { srcLang: 'en', label: 'English', src: '/en.vtt' }]}. The MDN description of the track element says that srclang is required for kind="subtitles". In this code, srcLang becomes the language of the TextTrack, and subtitles are selected by language. For this reason, the component does not support two subtitle tracks in the same language.

The first useEffect does the switching. The TextTrack mode has three values: disabled (not used), hidden (loaded but not displayed), and showing (displayed over the video). The code sets only the selected language to showing and the rest to disabled.

Subtitle files are loaded only when selected

Without a default attribute on <track>, mode starts as disabled. The MDN description says that a disabled track does not load its file. I used Playwright to operate the <select> and recorded the requests that reached the server and the state of each subtitle. The results were as follows.

Action Request to server Japanese subtitle English subtitle
Right after opening None disabled, cues is null disabled, cues is null
Select Japanese /ja.vtt showing, cues has 3 entries disabled, cues is null
Select English /en.vtt disabled, cues is null showing, cues has 3 entries
Select off None disabled, cues is null disabled, cues is null
Select Japanese again None showing, cues has 3 entries disabled, cues is null

Just opening the page requested no subtitle files. Only the file for the selected language was loaded. When I selected Japanese the second time, no request was sent. A track set back to disabled has cues set to null, even after it has been loaded.

This component does not put default on <track>, and it decides which subtitle to show using only state. The MDN description of mode also says that a default attribute is needed when building custom controls for Safari. I did not test Safari, so if you need Safari support, check this yourself.

Syncing the select when subtitles change from outside it

mode can also be changed from outside the <select>. For example, another script may rewrite mode. When that happens, the <select> can show a different subtitle than the one actually displayed. The second useEffect prevents this. The textTracks change event fires when a subtitle's mode changes, so the handler looks for showing tracks and puts the result into state.

At first, I wrote the handler to put the first showing track it found into state. While Japanese was displayed, I changed the English track's mode to showing from code. Both Japanese and English stayed showing, and the <select> still showed Japanese.

The cause was that the first showing track found was the Japanese one, which was already displayed. setLang('ja') sets the state to the same value it already has. When you update state to the same value, React skips the re-render. For that reason, the first useEffect did not run either.

So in the code above, among the showing tracks, I prefer one whose language differs from the current state. The current state is read by passing a function to setLang (the form of update based on the previous state, described in the React useState docs). With this version, the same operations produced the following results.

  • After setting the English track to showing: only English was showing, Japanese went back to disabled, and the <select> changed to English.
  • After then setting the English track to disabled: both were disabled, and the <select> changed to off.

The state changed to 'en', so the first useEffect ran and set Japanese to disabled.

Showing subtitles outside the video yourself

If you want the subtitles to appear large below the video, not over it, set mode to hidden. A hidden track loads its file and fires cuechange events in step with the time, but it draws nothing on the video. The cues to show right now are in activeCues, so you can put them into state and display them.

tsx
import { useEffect, useRef, useState } from 'react';
import type { Subtitle } from './SubtitledVideo';

// Don't draw the subtitles on top of the video; show them below it ourselves
export function CaptionBelow({ src, subtitle }: { src: string; subtitle: Subtitle }) {
  const trackRef = useRef<HTMLTrackElement>(null);
  const [text, setText] = useState('');

  useEffect(() => {
    const track = trackRef.current!.track;
    track.mode = 'hidden'; // Load the subtitles, but don't show them on top of the video
    const onCueChange = () => {
      const cues = Array.from(track.activeCues ?? []) as VTTCue[];
      setText(cues.map((c) => c.text).join('\n'));
    };
    track.addEventListener('cuechange', onCueChange);
    return () => track.removeEventListener('cuechange', onCueChange);
  }, []);

  return (
    <div>
      <video src={src} controls width={640}>
        <track ref={trackRef} kind="subtitles" src={subtitle.src} srcLang={subtitle.srcLang} label={subtitle.label} />
      </video>
      <p className="caption" aria-live="polite">{text}</p>
    </div>
  );
}

If you attach a ref to <track>, you can get its TextTrack directly from the track property of HTMLTrackElement. You don't have to count the index in textTracks.

I recorded the displayed text every second during playback. At 1.5, 2.5, and 3.6 seconds it showed "The cat is looking out the window." At 4.6 seconds, where there is no subtitle, it was empty. At 5.6 seconds it showed "A bird has flown in." When a subtitle's time ends, cuechange fires and activeCues becomes empty, so the display is cleared.

The video shows no subtitles on top of it. A dark band below the video shows "The cat is looking out the window."
The subtitles displayed below the video after setting mode to hidden (playback position 2.5 seconds)

The aria-live="polite" attribute on <p> tells screen readers that the content has changed. I did not test screen reader announcements.

What to check when subtitles don't appear

If a subtitle file fails to load, the <track> fires an error event, and its readyState becomes 3 (ERROR). The error is not shown on the page, so when subtitles don't appear, check the readyState of the <track> and the browser console. I tested the following five cases in Chromium.

Case Result
A file without the leading WEBVTT line The server returned 200, but the track got error. readyState was 3 and cues had 0 entries
A file returned with Content-Type: text/plain Loaded successfully. cues had 3 entries
Subtitles from a different origin (a server on another port), loaded without crossOrigin No request was sent, and the track got error. The console showed "Unsafe attempt to load URL …"
crossOrigin="anonymous" set, and the server does not return Access-Control-Allow-Origin error. The console showed an error saying CORS blocked the request
crossOrigin="anonymous" set, and the server returns Access-Control-Allow-Origin: * Loaded successfully. cues had 3 entries

A file without the WEBVTT line cannot be read as subtitles, even if the server returns it correctly. The request itself succeeded with 200, so the network log alone does not show the cause.

If the subtitle files are on a different origin from the page (for example, on a CDN), you must add crossOrigin to <video> and allow CORS on the subtitle server. The MDN description of the track element also says that src must be on the same origin as the document, unless the parent <video> has a crossorigin attribute. The reason SubtitledVideo accepts crossOrigin as a prop is for this case.

In the Chromium test environment, a file returned as text/plain loaded successfully. However, the MIME type for WebVTT is text/vtt, so configure the server to return text/vtt.

​Posted by 86