La condivisione di schede, finestre e schermi è possibile sulla piattaforma web con l'API Screen Capture. Il metodo getDisplayMedia()
consente all'utente di selezionare una schermata da acquisire come stream multimediale. Questo stream può quindi essere registrato con l'API MediaRecorder o condiviso con altri tramite la rete. La registrazione può essere salvata in un file locale tramite il metodo showOpenFilePicker()
.
L'esempio riportato di seguito mostra come registrare lo schermo dell'utente in formato WebM, visualizzare l'anteprima localmente nella stessa pagina e salvare la registrazione nel file system dell'utente.
let stream;
let recorder;
shareScreenButton.addEventListener("click", async () => {
// Prompt the user to share their screen.
stream = await navigator.mediaDevices.getDisplayMedia();
recorder = new MediaRecorder(stream);
// Preview the screen locally.
video.srcObject = stream;
});
stopShareScreenButton.addEventListener("click", () => {
// Stop the stream.
stream.getTracks().forEach(track => track.stop());
video.srcObject = null;
});
startRecordButton.addEventListener("click", async () => {
// For the sake of more legible code, this sample only uses the
// `showSaveFilePicker()` method. In production, you need to
// cater for browsers that don't support this method, as
// outlined in https://web.dev/patterns/files/save-a-file/.
// Prompt the user to choose where to save the recording file.
const suggestedName = "screen-recording.webm";
const handle = await window.showSaveFilePicker({ suggestedName });
const writable = await handle.createWritable();
// Start recording.
recorder.start();
recorder.addEventListener("dataavailable", async (event) => {
// Write chunks to the file.
await writable.write(event.data);
if (recorder.state === "inactive") {
// Close the file when the recording stops.
await writable.close();
}
});
});
stopRecordButton.addEventListener("click", () => {
// Stop the recording.
recorder.stop();
});
Supporto browser
MediaDevices.getDisplayMedia()
API MediaRecorder
showSaveFilePicker() dell'API File System Access
Per approfondire
- Specifica di acquisizione schermo W3C
- Specifiche di registrazione MediaStream W3C
- Specifiche dell'API File System Access del WICG