3

我正在使用navigator.mediaDevices.getDisplayMedia. 但是当我重新加载页面时,它停止了。我想自动继续录制。可能吗?

也许我可以以某种方式使用本地存储,重新加载的页面会尝试再次录制,但是再次出现选择要录制的屏幕的提示,但我想像以前一样选择相同的屏幕自动录制,这样每次重新加载页面后,用户都不会受到打扰。

有什么办法吗,也许服务人员可以解决这个问题?谢谢。

4

1 回答 1

2

MediaStream 绑定到其领域的负责文档。当此文档的权限策略更改或文档死亡(卸载)时,MediaStream 捕获的轨道将结束。

对于您的情况,唯一的方法是从您的用户必须一直保持打开的其他文档(弹出/选项卡)开始录制。

这是一个 plnkr演示了这一点,但这对于您的用户来说可能非常复杂......

在要记录的页面中:

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>")
}

并在弹出页面中

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;
  }
}
于 2020-12-10T07:16:51.047 回答