乐闻世界logo
搜索文章和话题

How to listen for "Stop sharing" click in Chrome DesktopCapture API

1个答案

1

When using the Chrome Desktop Capture API for screen sharing, you can detect when the user clicks 'Stop Sharing' by listening for specific browser events. This feature primarily involves capturing feedback from user interface interactions.

Step 1: Obtain the Screen Sharing Stream using navigator.mediaDevices.getDisplayMedia()

First, call the getDisplayMedia() method to request the user to share their screen. This method returns a Promise that resolves to a MediaStream object.

javascript
async function startScreenSharing() { try { const stream = await navigator.mediaDevices.getDisplayMedia({ video: true }); handleStream(stream); } catch (error) { console.error('Error: Unable to access display media.', error); } }

Step 2: Listen for the inactive Event on the Media Stream

When the user clicks the 'Stop Sharing' button on the browser interface, the MediaStream object triggers an inactive event. Respond to this event by adding an event listener to the stream.

javascript
function handleStream(stream) { stream.oninactive = () => { console.log('Screen sharing stopped by the user.'); // Perform cleanup here, such as closing related UI elements. }; // Use this stream, for example, to display it in a <video> element const videoElement = document.querySelector('video#screenVideo'); videoElement.srcObject = stream; }

Step 3: Practical Application

Place the above code in an appropriate location, such as in the click event handler of a button, to call startScreenSharing(). This way, when the user clicks the button, screen sharing begins, and you can detect when it stops.

Example Code Integration

javascript
document.getElementById('shareScreenBtn').addEventListener('click', () => { startScreenSharing(); }); async function startScreenSharing() { try { const stream = await navigator.mediaDevices.getDisplayMedia({ video: true }); handleStream(stream); } catch (error) { console.error('Error: Unable to access display media.', error); } } function handleStream(stream) { stream.oninactive = () => { console.log('Screen sharing stopped by the user.'); // Add code here to handle logic after stopping sharing }; const videoElement = document.querySelector('video#screenVideo'); videoElement.srcObject = stream; }

By implementing this approach, you can effectively detect and respond to the user clicking 'Stop Sharing' during screen sharing. This is crucial for ensuring your application correctly handles both the initiation and termination of screen sharing.

2024年8月18日 23:09 回复

你的答案