اشتراکگذاری برگهها، پنجرهها و صفحهها در بستر وب با Screen Capture API امکانپذیر است. متد getDisplayMedia()
به کاربر این امکان را میدهد تا صفحهای را انتخاب کند تا بهعنوان جریان رسانه عکس بگیرد. سپس این جریان را می توان با MediaRecorder API ضبط کرد یا با دیگران از طریق شبکه به اشتراک گذاشت. ضبط را می توان از طریق متد showOpenFilePicker()
در یک فایل محلی ذخیره کرد.
مثال زیر نشان میدهد که چگونه میتوانید صفحه کاربر را در قالب WebM ضبط کنید، به صورت محلی در همان صفحه پیشنمایش کنید و ضبط را در سیستم فایل کاربر ذخیره کنید.
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();
});