Skip to content

Commit

Permalink
GetDisplayMedia demo: make start button switch to stop button once sc…
Browse files Browse the repository at this point in the history
…reen sharing started in order to demonstrate stopping screen share from javascript
  • Loading branch information
eronnen committed Aug 20, 2023
1 parent feb561e commit 6a37c39
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/content/getusermedia/getdisplaymedia/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
'use strict';

const preferredDisplaySurface = document.getElementById('displaySurface');
const startButton = document.getElementById('startButton');
const startStopButton = document.getElementById('startButton');
const videoElement = document.querySelector('video');

if (adapter.browserDetails.browser === 'chrome' &&
adapter.browserDetails.version >= 107) {
Expand All @@ -21,16 +22,15 @@ if (adapter.browserDetails.browser === 'chrome' &&
}

function handleSuccess(stream) {
startButton.disabled = true;
startStopButton.textContent = 'Stop';
preferredDisplaySurface.disabled = true;
const video = document.querySelector('video');
video.srcObject = stream;
videoElement.srcObject = stream;

// demonstrates how to detect that the user has stopped
// sharing the screen via the browser UI.
stream.getVideoTracks()[0].addEventListener('ended', () => {
errorMsg('The user has ended sharing the screen');
startButton.disabled = false;
startStopButton.textContent = 'Start';
preferredDisplaySurface.disabled = false;
});
}
Expand All @@ -48,18 +48,27 @@ function errorMsg(msg, error) {
}


startButton.addEventListener('click', () => {
const options = {audio: true, video: true};
const displaySurface = preferredDisplaySurface.options[preferredDisplaySurface.selectedIndex].value;
if (displaySurface !== 'default') {
options.video = {displaySurface};
startStopButton.addEventListener('click', () => {
if (startStopButton.textContent === 'Start') {
const options = {audio: true, video: true};
const displaySurface = preferredDisplaySurface.options[preferredDisplaySurface.selectedIndex].value;
if (displaySurface !== 'default') {
options.video = {displaySurface};
}
navigator.mediaDevices.getDisplayMedia(options)
.then(handleSuccess, handleError);
}
else {
// demonstrates how to stop the stream from JavaScript
errorMsg('JavaScript has ended sharing the screen');
videoElement.srcObject.getTracks().forEach(track => track.stop());
videoElement.srcObject = null;
startStopButton.textContent = 'Start';
}
navigator.mediaDevices.getDisplayMedia(options)
.then(handleSuccess, handleError);
});

if ((navigator.mediaDevices && 'getDisplayMedia' in navigator.mediaDevices)) {
startButton.disabled = false;
startStopButton.disabled = false;
} else {
errorMsg('getDisplayMedia is not supported');
}

0 comments on commit 6a37c39

Please sign in to comment.