Questa guida illustra diversi approcci per la registrazione di audio e video da una scheda, una finestra o
uno schermo utilizzando API come browser.tabCapture o
getDisplayMedia().
Registrazione dello schermo
Per la registrazione dello schermo, chiama getDisplayMedia(), che attiva la finestra di dialogo
mostrata di seguito. In questo modo, l'utente può selezionare la scheda, la finestra o lo schermo che vuole
condividere e viene indicata chiaramente la registrazione in corso.
L'esempio seguente richiede l'accesso per registrare sia audio che video.
const stream = await navigator.mediaDevices.getDisplayMedia({ audio: true, video: true });
Se viene chiamato all'interno di uno script dei contenuti, la registrazione terminerà automaticamente quando l'utente passa a una nuova
pagina. Per registrare in background e durante la navigazione, utilizza un
documento fuori schermo con il motivo DISPLAY_MEDIA.
Acquisizione della scheda in base all'attivazione dall'utente
La chiamata a getDisplayMedia() fa sì che il browser mostri una finestra di dialogo che chiede all'utente cosa vuole condividere. Tuttavia, in alcuni casi l'utente ha appena fatto clic sul
pulsante di azione per richiamare l'estensione per una scheda specifica e vuoi
avviare immediatamente l'acquisizione della scheda senza questo prompt.
Registrare audio e video in background
A partire da Chrome 116, puoi chiamare l'API browser.tabCapture in un service worker
per ottenere un ID stream dopo l'attivazione dall'utente. che può essere passato a un documento fuori schermo per
avviare la registrazione.
Nel service worker:
browser.action.onClicked.addListener(async (tab) => {
const existingContexts = await browser.runtime.getContexts({});
const offscreenDocument = existingContexts.find(
(c) => c.contextType === 'OFFSCREEN_DOCUMENT'
);
// If an offscreen document is not already open, create one.
if (!offscreenDocument) {
// Create an offscreen document.
await browser.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['USER_MEDIA'],
justification: 'Recording from browser.tabCapture API',
});
}
// Get a MediaStream for the active tab.
const streamId = await browser.tabCapture.getMediaStreamId({
targetTabId: tab.id
});
// Send the stream ID to the offscreen document to start recording.
browser.runtime.sendMessage({
type: 'start-recording',
target: 'offscreen',
data: streamId
});
});
Poi, nel documento fuori schermo:
browser.runtime.onMessage.addListener(async (message) => {
if (message.target !== 'offscreen') return;
if (message.type === 'start-recording') {
const media = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: "tab",
chromeMediaSourceId: message.data,
},
},
video: {
mandatory: {
chromeMediaSource: "tab",
chromeMediaSourceId: message.data,
},
},
});
// Continue to play the captured audio to the user.
const output = new AudioContext();
const source = output.createMediaStreamSource(media);
source.connect(output.destination);
// TODO: Do something to record the MediaStream.
}
});
Per un esempio completo, consulta l'esempio Tab Capture - Recorder.
Registrare audio e video in una nuova scheda
Prima di Chrome 116, non era possibile utilizzare l'API browser.tabCapture in un service worker o utilizzare un ID stream creato da questa API in un documento offscreen. Entrambi questi
sono requisiti per l'approccio sopra descritto.
In alternativa, puoi aprire una pagina di estensione in una nuova scheda o finestra e ottenere direttamente uno stream. Imposta
la proprietà targetTabId per acquisire la scheda corretta.
Inizia aprendo una pagina di estensione (magari nel popup o nel service worker):
browser.windows.create({ url: browser.runtime.getURL("recorder.html") });
Poi, nella pagina dell'estensione:
browser.tabCapture.getMediaStreamId({ targetTabId: tabId }, async (id) => {
const media = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: "tab",
chromeMediaSourceId: id,
},
},
video: {
mandatory: {
chromeMediaSource: "tab",
chromeMediaSourceId: id,
},
},
});
// Continue to play the captured audio to the user.
const output = new AudioContext();
const source = output.createMediaStreamSource(media);
source.connect(output.destination);
});
In alternativa, valuta la possibilità di utilizzare l'approccio di registrazione dello schermo, che ti consente di registrare in background utilizzando un documento fuori schermo, ma mostra all'utente una finestra di dialogo per selezionare una scheda, una finestra o uno schermo da cui registrare.
Registrare l'audio in un popup
Se devi solo registrare l'audio, puoi ottenere direttamente uno stream nel popup dell'estensione utilizzando browser.tabCapture.capture. Quando il popup si chiude, la registrazione viene interrotta.
browser.tabCapture.capture({ audio: true }, (stream) => {
// Continue to play the captured audio to the user.
const output = new AudioContext();
const source = output.createMediaStreamSource(stream);
source.connect(output.destination);
// TODO: Do something with the stream (e.g record it)
});
Se hai bisogno che la registrazione persista durante la navigazione, valuta la possibilità di utilizzare l'approccio descritto nella sezione precedente.
Altre considerazioni
Per saperne di più su come registrare uno stream, consulta l'API MediaRecorder.