Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, not directly, because a MediaStreamTrack is not transferable. It's tied to the document it's created in.

A workaround would be to establish an RTCPeerConnection between the two tabs and transmit the screen-capture track from the tab that has it to the tab that doesn't. This should be relatively performant since the bits never leave your network card.

You can use a BroadcastChannel for the necessary signaling to establish such a connection, or do tricks with localStorage to do the signaling like I do here using a camera, but it works with any source (open in two tabs first, then click the Call button in one).

A limitation of this workaround is that if you close the original tab then you lose both tracks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...