这个小示例把浏览器选中的屏幕或窗口显示在当前页面的 video 元素中。代码到本地预览为止,没有建立远端 WebRTC 连接。
页面需要运行在支持该 API 的浏览器和安全上下文中,例如 HTTPS。点击按钮后,由浏览器让用户选择共享内容;停止共享时,清空预览。接口说明见 MDN getDisplayMedia。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Screen Capture with WebRTC</title> </head> <body> <h1>WebRTC Screen Capture Example</h1> <button onclick="startCapture()">Share Screen</button> <video id="videoElement" autoplay playsinline></video>
<script> async function startCapture() { const videoElement = document.getElementById('videoElement'); try { const stream = await navigator.mediaDevices.getDisplayMedia({ video: { cursor: "always", }, audio: false }); videoElement.srcObject = stream;
stream.getVideoTracks()[0].onended = function () { console.log('Screen sharing stopped'); videoElement.srcObject = null; }; } catch (err) { console.error("Error: " + err); } } </script> </body> </html>
|