Search code examples
javascriptgoogle-chrome-extensiongetusermediascreensharing

What is the correct way to handle native cancelling of getUserMedia screenshare?


I am using screenshare with getUserMedia for a web application I am developing.

I am currently using Chrome with a Chrome extension using the API below to achieve the functionality, but the functionality is also possible in Firefox and may become natively available(I believe it was possible in the past) via getDisplayMedia or other means in the future. https://developer.chrome.com/extensions/desktopCapture

During screenshare, a native dialog is shown at the bottom of the browser to stop the screenshare. I would like for a way to handle this event, but I am unaware of a common, standard way to achieve this. Is there an appropriate way to do this(preferably in all APIs), or should I achieve this by track events?


Solution

  • I am not quite sure as to how Chrome unspecified implementation behaves, but yes, you would normally have to listen to your VideoTrack's onended event.

    This snippet should work only in FF, which are the only one allowing non-chrome pages to access this feature.

    navigator.mediaDevices.getUserMedia({video: {mediaSource: 'screen'}}).then(stream => {
      document.getElementById('vid').srcObject = stream;
      const v_track = stream.getVideoTracks()[0];
      v_track.onended = e => console.log('stopped');
    }).catch(console.error);
    <video id="vid" autoplay></video>

    And in case it doesn't even work (because of StackSnippets© heavy security rules), here is a fiddle.