Continue recording with getDisplayMedia on page after reload

我只是一个虾纸丫 提交于 2021-02-10 14:26:54

问题


I'm recording my screen on a webpage with navigator.mediaDevices.getDisplayMedia. But when I reload the page, it stops. I'd like to automatically continue recording. Is it possible?

Maybe I could use the localstorage somehow, that the reloaded page would try to record again, but then the prompt to choose the screen to record appears again, but I'd like to have picked the same screen to record automatically as before, so that the users aren't bothered after every page reload.

Is there any way, maybe service workers could be the way? Thanks.


回答1:


A MediaStream is tied to its realm's responsible document. When this document's permission policy changes or if the document dies (unload), the MediaStream's captured tracks will end.

The only way around for your case, would be to start the recording from an other document (popup/tab) that your users would have to keep open the whole time.

Here is a plnkr demonstrating this, but that may be quite complex for your users to deal with...

In the page to record:

const button = document.querySelector( "button" );
const video = document.querySelector( "video" );
// We use a broadcast channel to let the popup window know we did reload
// When the popup receives the message
// it will set our video's src to its stream
const broadcast = new BroadcastChannel( "persistent-mediastream" );
broadcast.postMessage( "ping" );
// wait a bit for the popup has the time to set our video's src
setTimeout( () => {
  if( !video.srcObject ) { // there is no popup yet
    button.onclick = (evt) => {
      const popup = open( "stream-master.html" );
      clean();
    };
  }
  else {
    clean();
  }
}, 100);
function clean() {
  button.remove();
  document.body.insertAdjacentHTML("afterBegin", "<h4>You can reload this page and the stream will survive</h4>")
}

and in the popup page

let stream;
const broadcast = new BroadcastChannel( "persistent-mediastream" );
// when opener reloads
broadcast.onmessage = setOpenersVideoSource;

const button = document.querySelector( "button" );
// we need to handle an user-gesture to request the MediaStream
button.onclick = async (evt) => {
  stream = await navigator.mediaDevices.getDisplayMedia( { video: true } );
  setOpenersVideoSource();
  button.remove();
  document.body.insertAdjacentHTML("afterBegin", "<h4>Go back to the previous tab</h4>");
};
function setOpenersVideoSource() {
  if( opener ) {
    opener.document.querySelector( "video" ).srcObject = stream;
  }
}


来源:https://stackoverflow.com/questions/65227332/continue-recording-with-getdisplaymedia-on-page-after-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!