javascriptwebrtcmediastreamget-display-mediabroadcast-channel

How can I duplicate a media stream to a popup window?


I want to start a screen share in my main tab by calling getDisplayMedia, and then clone it to another popup window which I open from my app (using window.open), effectively showing the screen capture twice, in parallel.

According to this thread, this snippet should work - but it doesn't:

async function startCapture() {
  return await navigator.mediaDevices.getDisplayMedia();
}

function openPopup() {
  startCapture().then((stream) => {
    let video = document.getElementById("source");
    video.srcObject = stream;
    let popUpWindow = window.open("", "_blank", "x=y");
    let videoElem = document.createElement("video");
    videoElem.autoplay = true;
    let remoteVideo = popUpWindow.document.body.appendChild(videoElem);
    remoteVideo.srcObject = stream;
  });
}

What am I missing?


Solution

  • As @Kaiido mentioned in the comments, the issue was I needed to add the muted attribute to the destination video for it to play when automatically when duplicating the stream.

    More info here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

    Autoplay availability
    As a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true:

    • The audio is muted or its volume is set to 0
    • The user has interacted with the site (by clicking, tapping, pressing keys, etc.)
    • If the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features
    • If the autoplay feature policy is used to grant autoplay support to a and its document. Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the above are good guidelines to go by.