Sub topic 15
Detecting format support with canPlayType
This chapter assumes you can write basic HTML and JavaScript. You should know how to select elements, add event listeners, and read a function's return value. You should also know what a video element is and why source elements offer several formats. The earlier chapters on containers, codecs, and source cover that background.
Most pages never need to detect format support, because source elements let the browser choose a file. Some pages do need it. You may want to pick a file yourself, show a message before playback fails, or choose between two quality levels. In those cases, use canPlayType().
What canPlayType does
canPlayType() is a method of every audio and video element. It takes a string that describes a media type and returns one of three strings.
| Return value | Meaning |
|---|---|
| `""` (empty string) | The browser cannot play this type. |
| `"maybe"` | The browser cannot tell from the string alone. It might play. |
| `"probably"` | The browser believes it can play this type. |
The method never returns true or false. It also never returns "no". An empty string is falsy, but both "maybe" and "probably" are truthy, so a plain if test treats them the same.
const probe = document.createElement('video');
console.log(probe.canPlayType('video/webm; codecs="vp9, opus"'));
console.log(probe.canPlayType('video/mp4'));The first call names a container and two codecs. The second names only a container. In a typical current browser, the first call returns "probably" and the second returns "maybe". Your results depend on the browser and operating system.
Why the answer is not yes or no
A media type such as video/mp4 names only the container. An MP4 file can hold H.264, H.265, AV1, or other video codecs. The browser sees that it supports the container, but it does not know whether the codecs inside will work. So it answers "maybe".
When you add a codecs parameter, the browser can check each codec. If it supports all of them, it answers "probably". If it supports the container but not a listed codec, it answers "".
The more precise your string, the more useful the answer.
const probe = document.createElement('video');
const types = [
'video/mp4',
'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
'video/mp4; codecs="av01.0.05M.08"',
'video/webm; codecs="vp8, vorbis"',
'video/webm; codecs="vp09.00.10.08, opus"',
'video/ogg; codecs="theora, vorbis"'
];
for (const type of types) {
const answer = probe.canPlayType(type) || '(empty)';
console.log(`${answer.padEnd(10)} ${type}`);
}Run this in the console of several browsers and compare the output. The differences show why detection is sometimes worth the effort.
Writing the type string
The string follows the same format as the type attribute on a source element.
- Use a MIME type, such as
video/webm,video/mp4,audio/mpeg, oraudio/ogg. - To name codecs, add a semicolon and
codecs="...". Separate several codecs with commas. - Use double quotes around the codec list. In JavaScript, wrap the whole string in single quotes or a template literal.
- Use the codec identifiers that the format defines. For H.264 in MP4, a string like
avc1.42E01Eencodes the profile and level. For AAC,mp4a.40.2is the common identifier.
A wrong or misspelled codec string usually returns "". This looks the same as "unsupported", so check your strings carefully before you conclude that a browser lacks a codec.
A helper that picks the best source
A common use is to choose a file from a list ordered by preference. Check each candidate in order and use the first one the browser accepts.
function pickSource(candidates) {
const probe = document.createElement('video');
let fallback = null;
for (const candidate of candidates) {
const answer = probe.canPlayType(candidate.type);
if (answer === 'probably') {
return candidate;
}
if (answer === 'maybe' && fallback === null) {
fallback = candidate;
}
}
return fallback;
}
const choice = pickSource([
{ src: 'clip.av1.mp4', type: 'video/mp4; codecs="av01.0.05M.08"' },
{ src: 'clip.webm', type: 'video/webm; codecs="vp9, opus"' },
{ src: 'clip.mp4', type: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' }
]);
const video = document.querySelector('video');
if (choice) {
video.src = choice.src;
} else {
video.replaceWith('Sorry, this browser cannot play the video.');
}The function returns the first "probably" match. If there is none, it returns the first "maybe" match. If there are no matches at all, it returns null, and the page shows a message in place of the player.
This is the same job a list of source elements does. The difference is that your code now controls the decision. You can combine it with other facts, such as screen size or connection quality.
Limits and common errors
canPlayType() is a hint, not a guarantee. Keep these points in mind.
"probably"does not guarantee playback. The check looks at the type string. It does not read the file. A file can be corrupted, can use a codec profile or level the device cannot decode, or can have a wrong MIME type on the server."maybe"is not a failure. Many working files only produce"maybe"when you give a bare container type. Do not treat"maybe"as unsupported.- Truthiness hides the difference.
if (video.canPlayType(type))is true for both"maybe"and"probably". Compare against the strings when the difference matters. - Results vary by device. A phone may support a codec in hardware that a desktop lacks, or the reverse. Test on the devices your audience uses, and do not assume that one browser's answer applies to another.
- The check says nothing about delivery. Even with a supported format, playback can fail because of a missing file, wrong server headers, or a blocked cross-origin request. The server and CORS chapters cover those cases.
- Do not use it to guess the browser. Detect the feature you need, not the browser name. Browser support changes, and a feature check keeps working when it does.
A reliable page still handles failure after the fact. Listen for the error event on the element, and read video.error to see what went wrong.
const video = document.querySelector('video');
video.addEventListener('error', () => {
const err = video.error;
if (err && err.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
console.warn('The browser could not use this source.');
} else if (err) {
console.warn('Media error code:', err.code);
}
});The code MEDIA_ERR_SRC_NOT_SUPPORTED means the browser could not use the source. That covers unsupported formats, but it also covers missing files and bad MIME types.
When to use it
- Use
sourceelements when you only need the browser to pick among known files. This needs no script, and it is the default choice. - Use
canPlayType()when you must decide in code. Examples include choosing a quality level, loading a different player, or telling the user a format is unavailable before they press play. - Use
MediaSource.isTypeSupported()when you build an adaptive stream with Media Source Extensions. It checks support for that API instead, and the streaming chapter covers it.
Exercises
Exercise
A page calls video.canPlayType('video/mp4') and gets "maybe". A developer writes if (answer === 'probably') { play(); } else { showError(); }. Why can this logic wrongly show an error, and how would you fix it?
Show answer
A bare container type such as video/mp4 gives "maybe" even when the file plays fine, because the browser cannot see which codecs are inside. The code treats that as failure. Fix it in two ways: pass a type with a codecs parameter so the browser can answer "probably", and accept "maybe" as a usable answer, perhaps by trying the file and handling the error event if it fails.
Exercise
Write a call to canPlayType() that asks whether the browser can play WebM with VP9 video and Opus audio. What are the three possible return values?
Show answer
probe.canPlayType('video/webm; codecs="vp9, opus"'). The possible return values are "" (cannot play), "maybe" (cannot tell), and "probably" (believes it can play).
Exercise
A browser returns "probably" for a type, but the video still fails with MEDIA_ERR_SRC_NOT_SUPPORTED. Name two causes that canPlayType() cannot detect.
Show answer
Any two of these: the server sends the wrong MIME type; the file is missing or corrupted; the file uses a codec profile or level the device cannot decode; a cross-origin request is blocked. canPlayType() checks only the type string, not the file or its delivery.