Skip to content

The camera and the rest of the browser ​

Your view is a web page and has the features of any web page (full screen, sound, the clipboard, payment pages, downloads, the camera). Most of them work without any permission dialog. A few features such as the camera, the microphone and the location of the person, on the other hand, work only after the person allows them for your view in the webapp. world.askFor() asks the person for this permission.

Everything a web page can do ​

The webapp shows no permission dialog for these features:

  • full screen (element.requestFullscreen()), picture-in-picture, autoplay of sound and video and protected video (DRM)
  • writing to the clipboard (navigator.clipboard.writeText())
  • screen sharing (navigator.mediaDevices.getDisplayMedia()), the share sheet (navigator.share()) and the wake lock (navigator.wakeLock)
  • payments (the Payment Request API), the motion sensors of the phone and VR and AR
  • popups and new tabs (window.open(), target="_blank"), downloads and the dialogs of the browser (alert, confirm, prompt)
  • pointer lock and orientation lock for games, presentation on a second screen, forms and storage.

For some of them the browser itself may still ask the person as it does on any site (screen sharing, for example, always asks). That prompt belongs to the browser and the webapp has no part in it.

Your view can never move the page of the webapp to another address. Both window.top.location = … and links with target="_top" are blocked.

Features that need the person's yes ​

For some features the browser asks for permission on behalf of the top-level site and remembers the answer for that whole site. Because unaiverse.io is the site that shows your view, the prompt would read "unaiverse.io wants to use your camera" and a permission given to one view would hold for every view of every world.

The webapp therefore asks for these features itself in a dialog that names your site. Your view can use them only after the person allows them there.

BrowserFeatureWhat the webapp calls it
'camera'the camera
'microphone'the microphone
'geolocation'your location
'clipboard-read'reading what you copied
'midi'MIDI instruments
'usb'USB devices
'serial'serial ports
'hid'controllers and other connected devices
'bluetooth'Bluetooth devices
'idle-detection'knowing when you are not using the device
'local-fonts'the fonts you installed

world.webapp.allowed lists the features that the person has already allowed for your view.

Ask with askFor ​

js
if (!world.webapp.allowed.includes('camera')) {
  await world.askFor(['camera', 'microphone']);
}

askFor(features) opens a dialog in the webapp that asks the person to let your view use features. The dialog names your site and the features and says three things: (1) the permission holds only for your view and only on that device, (2) your view reloads once the person allows them and (3) the browser may then ask again on behalf of UNaIVERSE. Like the consent given when the person first opened your view, the dialog also states that the person and not UNaIVERSE is responsible for what happens in your view (Going live).

  • When every feature you name is already allowed, askFor resolves with true immediately and shows no dialog.
  • Unknown names are ignored.
  • One call with every feature you need gives the person a single dialog and reloads your view only once.
  • Dialogs are shown one at a time. A second call made while the first dialog is open waits for the answer to the first.

TIP

Call askFor when the person uses the feature (a press on Take a photo) and not when your view opens. A person who never needs the camera then never sees the dialog.

After a yes ​

Because the browser decides which features a page may use when it loads the page, the webapp reloads your view with the new features after the person allows them:

  1. askFor resolves with true.
  2. A moment later the webapp loads your page again at the last path that your view wrote with setPath (Links and the back button).
  3. Your view starts and connects again and finds the features in world.webapp.allowed.
  4. When it uses one of them through a call such as getUserMedia, the browser asks too on behalf of UNaIVERSE as it does on any site. The answer of the person to this prompt is the last step.

Code placed after await world.askFor(...) must not start the camera because it runs in a page that the reload is about to discard. Split the work in two:

  • before calling askFor, write with setPath('/camera') the path of the part of the view that uses the feature (the reload opens your view at that path)
  • at startup, start the feature when the path is that one and the feature is in allowed.

The webapp stores the permission on that device for the address of your view. On the next visit your view finds the feature in allowed from the start. When the person asks the webapp to forget the world, the permission is deleted with it.

After a no ​

When the person refuses, askFor rejects with the code 'declined'. While your view stays open every later call rejects with 'declined' without showing the dialog again. A view that stops working after a refusal leaves the person nothing to do but close it. Your view has to offer an alternative instead. A photo upload with <input type="file" accept="image/*"> needs no camera permission. In the same way a typed address replaces the location and a paste box replaces reading the clipboard.

askFor also rejects with 'unavailable' when the webapp cannot allow those features. Handle that code like a refusal:

js
try {
  await world.askFor(['geolocation']);
} catch (error) {
  // 'declined' or 'unavailable': offer to type the city instead.
  showCityField();
}

The camera ​

The example below combines these steps. Its button calls askFor and the view asks the browser for the camera after the reload. In this documentation the frame of the example does not allow the camera and the browser blocks it and the example shows the resulting error. Open runs the example in a tab of its own.

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world to build with: no account, no network.
const studio = { name: 'Drawing class', now: { text: 'Show us your drawing' } };

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: studio } });
	const [status, setStatus] = useState('Press the button to start.');
	const [isDeclined, setIsDeclined] = useState(false);
	const videoRef = useRef(null);
	const isAllowed = Boolean(world?.webapp.allowed.includes('camera'));

	// First the question of the browser, then the picture. Any failure gets a friendly message.
	async function startCamera() {
		try {
			videoRef.current.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
			setStatus('The camera is on.');
		} catch (problem) {
			setStatus(`The camera did not start (${problem.name}). You can still describe your drawing.`);
		}
	}

	async function onStart() {
		// Allowed for this view already: start.
		if (isAllowed) return startCamera();
		try {
			// After a yes, the webapp loads the view again at its last path: come back here.
			await world.setPath('/camera');
			await world.askFor(['camera']);
		} catch {
			// 'declined': the person said no in the webapp. Do not ask again.
			setStatus('No camera for this view. You can still describe your drawing.');
			setIsDeclined(true);
		}
	}

	// Loaded again after a yes: the camera is now allowed, and the view starts where the person was.
	useEffect(() => {
		if (isAllowed && window.location.pathname === '/camera') startCamera();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isAllowed]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	return (
		<>
			<p>{world ? status : 'Connecting…'}</p>
			<button onClick={onStart} disabled={!world || isDeclined}>Start the camera</button>
			<video ref={videoRef} autoPlay muted playsInline style={{ display: 'block', width: '100%', maxWidth: 320 }} />
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with: no account, no network.
const studio = { name: 'Drawing class', now: { text: 'Show us your drawing' } };

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: studio } });

const status = document.createElement('p');
status.textContent = 'Press the button to start.';
const button = document.createElement('button');
button.textContent = 'Start the camera';
const video = document.createElement('video');
video.autoplay = true;
video.muted = true;
video.playsInline = true;
video.style.cssText = 'display: block; width: 100%; max-width: 320px;';
document.body.append(status, button, video);

// First the question of the browser, then the picture. Any failure gets a friendly message.
async function startCamera() {
	try {
		video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
		status.textContent = 'The camera is on.';
	} catch (error) {
		status.textContent = `The camera did not start (${error.name}). You can still describe your drawing.`;
	}
}

button.onclick = async () => {
	// Allowed for this view already: start.
	if (world.get().webapp.allowed.includes('camera')) {
		startCamera();
		return;
	}
	try {
		// After a yes, the webapp loads the view again at its last path: come back here.
		await world.setPath('/camera');
		await world.askFor(['camera']);
	} catch (error) {
		// 'declined': the person said no in the webapp. Do not ask again.
		status.textContent = 'No camera for this view. You can still describe your drawing.';
		button.disabled = true;
	}
};

// Loaded again after a yes: the camera is now allowed, and the view starts where the person was.
if (location.pathname === '/camera' && world.webapp.allowed.includes('camera')) startCamera();
Live, on a fake world
Open

getUserMedia can fail for reasons outside your code. Always catch the error and keep your view usable.

error.nameUsually means
NotAllowedErrorThe person refused the prompt of the browser or the feature is not allowed for your view.
NotFoundErrorThere is no camera (or microphone) on this device.
NotReadableErrorAnother app is using the camera.
OverconstrainedErrorNo camera matches what you asked for (a size, the back camera).

Stopping every track when your view no longer needs the camera also turns off its light:

js
video.srcObject?.getTracks().forEach((track) => track.stop());
video.srcObject = null;

To send a frame of the camera to the world, draw it on a canvas and send the canvas as an image (Send a photo from the camera). Tutorial: an agent with a camera builds a complete view around the camera.

The person's location ​

The location of the person needs 'geolocation':

js
if (!world.webapp.allowed.includes('geolocation')) {
  await world.setPath('/near-me');
  await world.askFor(['geolocation']); // with a yes, the view loads again at /near-me
} else {
  navigator.geolocation.getCurrentPosition(
    (position) => showNearby(position.coords.latitude, position.coords.longitude),
    () => showCityField(), // the browser said no, or gave no position: offer to type it
    { timeout: 10000 },
  );
}

Ask only for what you need. A city is often enough and the person can type it (Use the person's location).

The clipboard ​

Writing needs no permission. Browsers require the call to come from a click:

js
button.onclick = async () => {
  await navigator.clipboard.writeText(world.get().data.code);
  button.textContent = 'Copied';
};

Reading (navigator.clipboard.readText()) needs 'clipboard-read'. A text field where the person pastes is often simpler and needs no permission.

Popups: logins and payments ​

window.open() and links with target="_blank" open a normal window or tab for a payment page, a login with another service or your help pages.

Pitfall

The window you open cannot communicate with your view. The webapp keeps its windows apart from those of other sites. A window opened from your view therefore has an empty window.opener and your view can neither watch it nor send it messages. Cookies do not pass between the two either. Your view is a page of your site embedded in another site. Such a page usually does not see the cookies that your site stores when it is opened on its own and on an iPhone it never sees them.

The result of a login or a payment reaches your view through your server:

  1. Your view asks your server to start the flow and gets an address with a one-time code. A sign-in page of your site opened in this way also lets your server learn for certain who the person is (Who the person is).
  2. Your view opens that address with window.open().
  3. At the end the payment provider redirects that window to a page of your site. Your server records the result under the code while the page tells the person to close the window.
  4. Your view polls your server for the result every few seconds and once more when the person comes back (document.addEventListener('visibilitychange', …)).

Downloads ​

Downloads are allowed. Build the file in the page and hand it to the person with a link that has the download attribute:

js
const csv = world.get().members.map((member) => `${member.name},${member.role}`).join('\n');
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
link.download = 'members.csv';
link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 1000); // free the file once the download started

A link to a file on your server served with Content-Disposition: attachment works too (Download a file from data).

Storage ​

localStorage, sessionStorage and IndexedDB work in your view with two differences from your site opened on its own:

  • browsers keep the storage of a page embedded in another site apart from the storage of the same site opened directly (what your view stores is invisible to your site and vice versa)
  • browsers clear this storage more readily.

Keep small preferences there (a chosen tab, a collapsed panel) and everything that matters on your server.

While you build ​

With a fake world:

  • every feature counts as allowed and world.webapp.allowed lists them all
  • askFor resolves with true and nothing reloads
  • the browser itself still prompts for the camera, the microphone and the location like on any local page (they work because browsers treat localhost as a secure context).

To see your view as a person who has allowed nothing yet, pass an empty list:

js
const world = await connectToHost({ fake: { world: studio }, webapp: { allowed: [] } });

The branch of your code that calls askFor then runs and askFor still resolves with true. To test a refusal, call your error branch with the object { code: 'declined' }. Finally try the whole flow with the dialog, the reload and the prompt of the browser in the webapp and on a phone. Going live covers writing the address of your view in the Own view field of one of your worlds.

Next steps ​

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