Chiedi la fotocamera solo quando serve
Una vista può usare la fotocamera solo dopo che la persona l'ha permessa due volte: nella webapp (un permesso che vale solo per la tua vista) e nel browser. Una richiesta fatta all'apertura della vista arriva prima che la persona abbia un motivo per dire sì. Chiedi invece nell'handler del clic del controllo che usa la fotocamera. world.webapp.allowed elenca le funzioni che la persona ha già permesso alla tua vista e world.askFor([...]) chiede le altre. Dove manca la fotocamera o il browser la blocca (come può succedere nel riquadro qui sotto) l'esempio lo dice. Premi Open per provarlo in una scheda a parte.
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The fake world is a photo booth, with no account and no network.
const booth = { name: 'Photo booth', now: { text: 'Smile!' } };
// True when the view was loaded at the place of the camera (?camera=on), which startCamera writes.
const isCameraPlace = new URLSearchParams(location.search).get('camera') === 'on';
export default function App() {
// While building: the fake world (every feature allowed). In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: booth } });
const [note, setNote] = useState('The camera is off.');
const [isOn, setIsOn] = useState(false);
const video = useRef(null);
async function startCamera() {
try {
// 1. The yes in the webapp, for this view only (asked once).
if (!world.webapp.allowed.includes('camera')) {
// Write the place of the camera first, because after a yes the webapp loads the view again at the last path written.
await world.setPath(`${location.pathname}?camera=on`);
await world.askFor(['camera']);
return;
}
// 2. The browser asks its own question (the first time) and then gives the picture.
video.current.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
setIsOn(true);
setNote('The camera is on.');
} catch (error) {
// 'declined' means the person said no in the webapp. Any other error comes from a browser that could not start the camera.
setNote(error.code === 'declined'
? 'You said no: the view works without the camera.'
: `No camera could start here (${error.name}).`);
}
}
// After a yes in the webapp, the view loads again at this place, and the camera starts at once because the person already asked for it.
const isBackForCamera = world !== null && isCameraPlace && world.webapp.allowed.includes('camera');
useEffect(() => {
if (isBackForCamera) startCamera();
// This runs once, when the world arrives.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isBackForCamera]);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Ask only when the person wants the camera, never when the view opens.
return (
<>
<p>{world.now?.text}</p>
{/* playsInline plays the video in the page on a phone, not full screen. */}
<video ref={video} hidden={!isOn} autoPlay muted playsInline style={{ width: 240 }} />
<button onClick={startCamera}>Start the camera</button>
<p>{note}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The fake world is a photo booth, with no account and no network.
const booth = { name: 'Photo booth', now: { text: 'Smile!' } };
// True when the view was loaded at the place of the camera (?camera=on), which startCamera writes.
const isCameraPlace = new URLSearchParams(location.search).get('camera') === 'on';
// While building: the fake world (every feature allowed). In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: booth } });
const now = document.createElement('p');
const video = document.createElement('video');
video.hidden = true;
video.autoplay = true;
video.muted = true;
video.playsInline = true; // on a phone, play in the page and not full screen
video.style.width = '240px';
const start = document.createElement('button');
start.textContent = 'Start the camera';
const note = document.createElement('p');
note.textContent = 'The camera is off.';
document.body.append(now, video, start, note);
async function startCamera() {
try {
// 1. The yes in the webapp, for this view only (asked once).
if (!world.webapp.allowed.includes('camera')) {
// Write the place of the camera first, because after a yes the webapp loads the view again at the last path written.
await world.setPath(`${location.pathname}?camera=on`);
await world.askFor(['camera']);
return;
}
// 2. The browser asks its own question (the first time) and then gives the picture.
video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
video.hidden = false;
note.textContent = 'The camera is on.';
} catch (error) {
// 'declined' means the person said no in the webapp. Any other error comes from a browser that could not start the camera.
note.textContent = error.code === 'declined'
? 'You said no: the view works without the camera.'
: `No camera could start here (${error.name}).`;
}
}
// Ask only when the person wants the camera, never when the view opens.
start.onclick = startCamera;
// After a yes in the webapp, the view loads again at this place, and the camera starts at once because the person already asked for it.
if (isCameraPlace && world.webapp.allowed.includes('camera')) startCamera();
// Called at once, then after every change of the world.
world.subscribe((node) => {
now.textContent = node.now?.text ?? '';
});Come funziona
- Quando
'camera'non è inworld.webapp.allowed,world.askFor(['camera'])apre una finestra di dialogo della webapp che nomina il tuo sito. - Dopo un sì la webapp carica di nuovo la tua vista con la fotocamera permessa. La carica all'ultimo percorso che la tua vista ha passato a
setPath. Per questo il codice scrive prima un percorso che accende la fotocamera (setPath('...?camera=on')). Caricata di nuovo a quel percorso, la vista trova la fotocamera permessa e la accende senza un secondo clic. getUserMediamostra poi la richiesta di permesso del browser (solo la prima volta) e si risolve con lo stream video.- Dopo un no
askForviene rifiutata con il codice'declined'e ogni chiamata successiva viene rifiutata allo stesso modo finché la tua vista resta aperta. Non chiedere di nuovo e offri quello che funziona senza fotocamera.
Le funzioni che hanno bisogno del sì della persona spiega perché la webapp chiede prima del browser ed elenca le altre funzioni che si comportano allo stesso modo. Con un mondo finto ogni funzione conta come permessa e l'esempio passa subito alla richiesta di permesso del browser.
Vedi anche
askFor- La fotocamera e il resto del browser
- Invia una foto dalla fotocamera
Camera: un componente fotocamera pronto.- Tutorial: un agente con la fotocamera