Urgent.News

What's breaking now, across thousands of outlets.

Culture

Add casting to a custom HTML5 video player without breaking it

TL;DR We're adding a cast button to a custom <video> player using the Remote Playback API, with an AirPlay fallback for Safari. Then we fix the four bugs that make casting work on your laptop and fail on an actual TV: token expiry, CORS on the receiver, unreachable hosts, and treating prompt() as if it were a connection. The thing to understand before writing any code: the TV does not run your…

Adding a cast button to a custom HTML5 video player without disrupting its functionality can be achieved using the Remote Playback API, along with a fallback for Safari's AirPlay feature. To ensure that casting works on laptops and TVs, four potential issues must be addressed: token expiry, CORS on the receiver, unreachable hosts, and treating prompt() as a connection.

Initial setup involves a basic HTML structure with a video element, a cast button, and a container for displaying the state. The accompanying JavaScript file (player.js) imports the HLS.js library for handling HLS manifest files. The code checks for the player's support of the MPEG URL format and loads the stream accordingly. It is crucial to note that the TV does not run the player; instead, it fetches the stream URL and plays it with its own stack.

Overlays, quality caps, analytics, and token refresh logic are not transferred, which adds complexity to casting code.

Feature detection is implemented across three methods to support various browsers: the standards-based path using remote Playback API, Safari's AirPlay interface, and the Cast SDK. The detectCastSupport function returns an object containing information about each path's availability.

For Remote Playback, two main calls are made: watchAvailability, which checks whether a device is reachable and determines whether to display the button, and prompt(), which opens the browser's device picker. The code ensures that the button is hidden if a device is not reachable or if the user dismisses the picker, preventing errors. The connecting event listener is used to update the onState function with the current state of the casting process.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Culture

More from Wednesday 16 September →