HTML Audio & Video
HTML DOM Video canPlayType() Method
The canPlayType() method asks the browser whether it thinks it can play a given media type. It works on both audio and video elements (both inherit it from HTMLMediaElement) and is the standard way to feature-detect format support before choosing a source.
Definition and Usage
canPlayType() takes a MIME type string, optionally including a codecs parameter, and returns how confident the browser is that it can play that format. It never actually loads or plays anything; it only reports an opinion, which is why the answer is deliberately vague.
Syntax
mediaElement.canPlayType(type)The type parameter is a string such as "video/mp4" or, more precisely, "video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"". The method returns one of three possible strings.
| Return value | Meaning |
|---|---|
| "probably" | The browser is fairly confident it can play this type |
| "maybe" | The browser cannot decide without trying to load the media |
| "" (empty string) | The browser is certain it cannot play this type |
Example: feature detection
const video = document.createElement("video");
const mp4 = video.canPlayType("video/mp4");
const webm = video.canPlayType("video/webm");
const ogg = video.canPlayType('video/ogg; codecs="theora"');
console.log("MP4:", mp4 || "no");
console.log("WebM:", webm || "no");
console.log("OGG:", ogg || "no");Because the empty string is falsy, you can treat any non-empty result as "supported". A robust loader checks each candidate format and picks the first that returns "probably" or "maybe".
function pickSource(video, candidates) {
for (const c of candidates) {
if (video.canPlayType(c.type)) {
video.src = c.src;
return c.type;
}
}
return null; // none supported
}Always include the codecs parameter when you can. Without it a browser may only answer "maybe", because container support alone does not guarantee the codec inside is decodable.
