How to detect and connect to Google Cast devices and handle Media Session API?

I am trying to implement a feature that allows me to discover and connect to Google Cast devices (such as Google Nest Hub or Chromecast) directly from a web page. I would also like to handle the Media Session API to control audio/video playback via a Cast device.