Listing 1: Verfügbarkeit der WebXR API prüfen und das Polyfill einbindenwindow.addEventListener("load", async () => {
  const startButton = document.querySelector("#start");
  startButton.addEventListener("click", handleStartClick);
   if (!navigator.xr) {
    polyfill = new WebXRPolyfill();
  } else if (navigator.xr.isSessionSupported) {
    try {
      const supported = await navigator.xr.isSessionSupported("immersive-vr");
      if (!supported) {
        startButton.disabled = true;
      }
    } catch (e) {
      console.error('Error checking the availability of the session type');
    }
  }
});

Listing 2: Die XRSession startenlet xrSession = null;
let animationFrameId = null;
async function handleStartClick() {
  if (!xrSession) {
    try {      xrSession = await navigator.xr.requestSession("immersive-vr");
    } catch (e) {
      console.error('There was an error requesting the session');
    }
    animationFrameId = xrSession.requestAnimationFrame(drawFrame);
  } else {
    try {
      await xrSession.end();
    } catch (e) {
      console.error('Could not end the existing session');
    }
  }
}


Listing 3: Die requestAnimationFrame-Methode einsetzenlet lastFrameTime = 0;
function drawFrame(time, frame) {
  let pose = frame.getViewerPose(xrReferenceSpace);  
  animationFrameId = frame.session.requestAnimationFrame(drawFrame);
  if (pose) {
    const deltaT = (time - lastFrameTime);
    lastFrameTime = time;
    for (let view of pose.views) {
      render(view, deltaT);
    }
  }
}
function render(view, deltaT) {
  // webGL magic happens here
}


Listing 4: Die Sitzung beendenfunction handleSessionEnded() {
  if (animationFrameId) {    xrSession.cancelAnimationFrame(animationFrameId);
    animationFrameId = null;
  }
  xrSession = null;
}
window.addEventListener("load", async () => {
  const endButton = document.querySelector("#end");
  endButton.addEventListener("click", handleSessionEnded);
});
async function handleStartClick() {
  ...
  xrSession.addEventListener("end", handleSessionEnded);
}

