88'use strict' ;
99
1010const preferredDisplaySurface = document . getElementById ( 'displaySurface' ) ;
11- const startButton = document . getElementById ( 'startButton' ) ;
11+ const startStopButton = document . getElementById ( 'startButton' ) ;
12+ const videoElement = document . querySelector ( 'video' ) ;
1213
1314if ( adapter . browserDetails . browser === 'chrome' &&
1415 adapter . browserDetails . version >= 107 ) {
@@ -21,16 +22,15 @@ if (adapter.browserDetails.browser === 'chrome' &&
2122}
2223
2324function handleSuccess ( stream ) {
24- startButton . disabled = true ;
25+ startStopButton . textContent = 'Stop' ;
2526 preferredDisplaySurface . disabled = true ;
26- const video = document . querySelector ( 'video' ) ;
27- video . srcObject = stream ;
27+ videoElement . srcObject = stream ;
2828
2929 // demonstrates how to detect that the user has stopped
3030 // sharing the screen via the browser UI.
3131 stream . getVideoTracks ( ) [ 0 ] . addEventListener ( 'ended' , ( ) => {
3232 errorMsg ( 'The user has ended sharing the screen' ) ;
33- startButton . disabled = false ;
33+ startStopButton . textContent = 'Start' ;
3434 preferredDisplaySurface . disabled = false ;
3535 } ) ;
3636}
@@ -48,18 +48,27 @@ function errorMsg(msg, error) {
4848}
4949
5050
51- startButton . addEventListener ( 'click' , ( ) => {
52- const options = { audio : true , video : true } ;
53- const displaySurface = preferredDisplaySurface . options [ preferredDisplaySurface . selectedIndex ] . value ;
54- if ( displaySurface !== 'default' ) {
55- options . video = { displaySurface} ;
51+ startStopButton . addEventListener ( 'click' , ( ) => {
52+ if ( startStopButton . textContent === 'Start' ) {
53+ const options = { audio : true , video : true } ;
54+ const displaySurface = preferredDisplaySurface . options [ preferredDisplaySurface . selectedIndex ] . value ;
55+ if ( displaySurface !== 'default' ) {
56+ options . video = { displaySurface} ;
57+ }
58+ navigator . mediaDevices . getDisplayMedia ( options )
59+ . then ( handleSuccess , handleError ) ;
60+ }
61+ else {
62+ // demonstrates how to stop the stream from JavaScript
63+ errorMsg ( 'JavaScript has ended sharing the screen' ) ;
64+ videoElement . srcObject . getTracks ( ) . forEach ( track => track . stop ( ) ) ;
65+ videoElement . srcObject = null ;
66+ startStopButton . textContent = 'Start' ;
5667 }
57- navigator . mediaDevices . getDisplayMedia ( options )
58- . then ( handleSuccess , handleError ) ;
5968} ) ;
6069
6170if ( ( navigator . mediaDevices && 'getDisplayMedia' in navigator . mediaDevices ) ) {
62- startButton . disabled = false ;
71+ startStopButton . disabled = false ;
6372} else {
6473 errorMsg ( 'getDisplayMedia is not supported' ) ;
6574}
0 commit comments