Search code examples
javascriptreactjswebrtc

Screen sharing screen does not display after choosing screen using Reactjs and WebRTC


I can click the share screen and choose screens that I want but nothing displays in the video after I clicked it.

I want to display the screen that I have clicked or choose.

Share screen function:

const shareScreen = () => {
  var displayMediaStreamConstraints = {
    video: true // or pass HINTS
    };
    
    if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia(displayMediaStreamConstraints);
    } else {
        navigator.getDisplayMedia(displayMediaStreamConstraints);
    }
};

Video component

            <Paper className={classes.paper}>
                <Grid item xs={12} md={6}>
                    <Typography variant="h5" gutterBottom>{name || 'Name'}</Typography>
                    <video playsInline muted ref={myVideo} autoPlay className={classes.video} />
                </Grid>
                 <button onClick={shareScreen}>Share Screen</button>
            </Paper>

Solution

  • getDisplayMedia doesn't display anything, it returns a promise that resolves to a stream. In order to display the video, you need to wait for the promise to resolve then assign the stream to the srcObject field of an HTMLVideoElement.

    let video = document.getElementById('uservideo');
    let stream = await navigator.mediaDevices.getDisplayMedia(constraints);
    video.srcObject = stream;