-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
105 lines (76 loc) · 2.77 KB
/
script.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// -------------------------------
// VARIABLES PLACE
// -------------------------------
// --- DOM ELEMENTS ---
const
videoElement = document.querySelector('.video'),
captureButton = document.querySelector('.capture-button'),
showStreamButton = document.querySelector('.show-stream'),
eyeImage = document.querySelector('.show-stream img');
// --- STATE OF THE PICTURE IN PICTURE ---
let
pictureIsInPicture = false,
mediaStreamExists = false;
// ------------------------------------
// WORKING WITH THE SCREEN CAPTURE API
// ------------------------------------
async function selectMediaStream() {
try {
// => capturing screen contents as a live mediaStream
const mediaStream = await navigator.mediaDevices.getDisplayMedia();
// => link the media stream with the video element, to have a stage
videoElement.srcObject = mediaStream;
// => activate the media stream automatically
videoElement.onloadedmetadata = async () => {
videoElement.play();
};
mediaStreamExists = videoElement.srcObject;
} catch (error) {
alert(error);
}
}
// => stop current stream
const stopStreamedVideo = (videoElem) => {
const stream = videoElem.srcObject;
const tracks = stream.getTracks();
tracks.forEach((track) => {
track.stop();
});
videoElem.srcObject = null;
mediaStreamExists = videoElem.srcObject;
}
// => show the captured media stream
captureButton.addEventListener('click', async () => {
captureButton.disabled = true;
if(!mediaStreamExists){
await selectMediaStream();
}
else if(mediaStreamExists){
stopStreamedVideo(videoElement);
// => if no stream exist, capture a new target
mediaStreamExists || await selectMediaStream();
}
captureButton.disabled = false;
captureButton.innerHTML = !mediaStreamExists ? 'Capture' : 'New Capture' ;
showStreamButton.style.display = !mediaStreamExists ? 'none' : 'block';
});
// note:
// the requestPictureInPicture method needs an explicit user action and can`t start automatically
// => show or hide the stream
showStreamButton.addEventListener('click', async()=>{
if(!pictureIsInPicture){
// => call the requestPictureInPicture method of the HTMLVideoElement
await videoElement.requestPictureInPicture();
pictureIsInPicture = true;
} else if (pictureIsInPicture) {
try{
// => close the picture in picture
await document.exitPictureInPicture();
pictureIsInPicture = false;
} catch(error) {
stopStreamedVideo(videoElement);
location.reload();
}
}
eyeImage.src = !pictureIsInPicture ? './view.png' : './hide.png';
})