Skip to content

Ask for the camera only when needed ​

A view can use the camera only after the person allows it twice: in the webapp (a permission that covers your view alone) and in the browser. A request made when the view opens comes before the person has any reason to say yes. Ask instead in the click handler of the control that uses the camera. world.webapp.allowed lists the features the person has already allowed your view and world.askFor([...]) asks for the others. Where there is no camera or the browser blocks it (as it may in the frame below) the example says so. Press Open to try it in a tab of its own.

jsx
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>
		</>
	);
}
js
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 ?? '';
});
Live, on a fake world
Open

How it works ​

  1. When 'camera' is not in world.webapp.allowed, world.askFor(['camera']) opens a dialog of the webapp that names your site.
  2. After a yes the webapp loads your view again with the camera allowed. It loads the view at the last path that your view passed to setPath. For this reason the code first writes a path that turns the camera on (setPath('...?camera=on')). Loaded again at that path, the view finds the camera allowed and turns it on without a second click.
  3. getUserMedia then shows the permission prompt of the browser (only the first time) and resolves with the video stream.
  4. After a no askFor rejects with the code 'declined' and every later call rejects the same way while your view stays open. Do not ask again and offer what works without the camera.

Features that need the person's yes explains why the webapp asks before the browser and lists the other features that work the same way. With a fake world every feature counts as allowed and the example goes straight to the permission prompt of the browser.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.