การแชร์แท็บ หน้าต่าง และหน้าจอสามารถทำได้บนแพลตฟอร์มเว็บด้วย 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();
});
การสนับสนุนเบราว์เซอร์
MediaDevices.getDisplayMedia()
MediaRecorder API
showSaveFilePicker() ของ File System Access API
อ่านเพิ่มเติม
- ข้อกำหนดการจับภาพหน้าจอของ W3C
- ข้อกำหนดการบันทึก MediaStream ของ W3C
- ข้อกำหนดการเข้าถึงระบบไฟล์ของ WICG