Search code examples
javascriptreactjsnavigator

screensharing "cancel button"


In my app, I have set up screenshare functionality - when a button is clicked, it calls navigator.mediaDevices.getDisplayMedia

After that, I capture, create a stream, add an event listener to it, establish a WebRTC connection and transmit via socket

One problem remains, if I press screenshare and cancel - how do I catch this event?

I can provide some details if needed.


Solution

  • Using getDisplayMedia Promise:

    When you call navigator.mediaDevices.getDisplayMedia, it returns a promise. This promise can be resolved with a MediaStream if the user accepts the screen sharing request or rejected if the user cancels it. To catch the event when the user cancels, you can attach a catch block to the promise chain.

    navigator.mediaDevices.getDisplayMedia({ video: true })
      .then(mediaStream => {
        // User accepted screen sharing
        // Set up WebRTC connection
      })
      .catch(error => {
        if (error.name === 'NotAllowedError') {
          // User cancelled screen sharing
          console.log('Screen sharing was cancelled by the user.');
        } else {
          // Handle other errors
          console.error('Error accessing screen sharing:', error);
        }
      });