const xr = navigator.xr;Starting up and shutting down a WebXR session
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
let webxrPolyfill = null;
function getXR(usePolyfill) {
let tempXR;
switch (usePolyfill) {
case "if-needed":
tempXR = navigator.xr;
if (!tempXR) {
webxrPolyfill = new WebXRPolyfill();
tempXR = webxrPolyfill;
}
break;
case "yes":
webxrPolyfill = new WebXRPolyfill();
tempXR = webxrPolyfill;
break;
case "no":
default:
tempXR = navigator.xr;
break;
}
return tempXR;
}
const nativeXr = getXR("no"); // Get the native XRSystem object
const polyfilledXr = getXR("yes"); // Always returns an XRSystem from the polyfill
const xr = getXR("if-needed"); // Use the polyfill only if navigator.xr missingconst immersiveOK = await navigator.xr.isSessionSupported("immersive-vr");
if (immersiveOK) {
// Create and use an immersive VR session
} else {
// Create an inline session instead, or tell the user about the
// incompatibility if inline is required
}xr.requestSession("immersive-vr").then((session) => {
xrSession = session;
/* continue to set up the session */
});async function createImmersiveSession(xr) {
session = await xr.requestSession("immersive-vr");
return session;
}async function createImmersiveSession(xr) {
session = await xr.requestSession("immersive-vr", {
requiredFeatures: ["unbounded"],
});
return session;
}async function createInlineSession(xr) {
session = await xr.requestSession("inline", {
optionalFeatures: ["local"],
});
return session;
}async function runSession(session) {
session.addEventListener("end", onSessionEnd);
const canvas = document.querySelector("canvas");
const gl = canvas.getContext("webgl", { xrCompatible: true });
// Set up WebGL data and such
const worldData = loadGLPrograms(session, "world-data.xml");
if (!worldData) {
return null;
}
// Finish configuring WebGL
worldData.session.updateRenderState({
baseLayer: new XRWebGLLayer(worldData.session, gl),
});
// Start rendering the scene
referenceSpace = await worldData.session.requestReferenceSpace("unbounded");
worldData.referenceSpace = referenceSpace.getOffsetReferenceSpace(
new XRRigidTransform(
worldData.playerSpawnPosition,
worldData.playerSpawnOrientation,
),
);
worldData.animationFrameRequestID =
worldData.session.requestAnimationFrame(onDrawFrame);
return worldData;
}session.onvisibilitychange = (event) => {
switch (event.session.visibilityState) {
case "hidden":
myFrameRate = 10;
break;
case "blurred-visible":
myFrameRate = 30;
break;
case "visible":
default:
myFrameRate = 60;
break;
}
};async function shutdownXR(session) {
if (session) {
await session.end();
/* At this point, WebXR is fully shut down */
}
}session.onend = (event) => {
/* the session has shut down */
freeResources();
};