-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrecording_screen.js
More file actions
80 lines (66 loc) · 2.26 KB
/
recording_screen.js
File metadata and controls
80 lines (66 loc) · 2.26 KB
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
const fetchBlob = async (url) => {
const response = await fetch(url);
const blob = await response.blob();
const base64 = await convertBlobToBase64(blob);
return base64;
};
const convertBlobToBase64 = (blob) => {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
};
});
};
chrome.runtime.onMessage.addListener((message) => {
if (message.name !== 'startRecordingOnBackground') {
return;
}
// Prompt user to choose screen or window
chrome.desktopCapture.chooseDesktopMedia(
['screen', 'window'],
function (streamId) {
if (streamId == null) {
return;
}
// Once user has chosen screen or window, create a stream from it and start recording
navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: streamId,
}
}
}).then(stream => {
const mediaRecorder = new MediaRecorder(stream);
const chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.onstop = async function(e) {
const blobFile = new Blob(chunks, { type: "video/webm" });
const base64 = await fetchBlob(URL.createObjectURL(blobFile));
// When recording is finished, send message to current tab content script with the base64 video
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
const tabWhenRecordingStopped = tabs[0];
chrome.tabs.sendMessage(tabWhenRecordingStopped.id, {
name: 'endedRecording',
body: {
base64,
}
})
window.close();
});
// Stop all tracks of stream
stream.getTracks().forEach(track => track.stop());
}
mediaRecorder.start();
}).finally(async () => {
// After all setup, focus on previous tab (where the recording was requested)
await chrome.tabs.update(message.body.currentTab.id, { active: true, selected: true })
});
})
});