WebXR and Compatible Browsers

Learn what WebXR is, its use cases, implementation, and the browsers that are compatible with it.

Get Started free
Home Guide WebXR – A Detailed Guide

WebXR – A Detailed Guide

By Shweta Jain, Community Contributor -

WebXR is a robust web API that delivers engaging experiences in virtual and augmented reality (VR and AR). With WebXR, developers can create interactive experiences that work efficiently across VR headsets, AR devices, and even standard desktop or mobile browsers.

It lets developers create truly immersive experiences that can be accessed and engaged by a larger audience.

This article delves deeper into WebXR and discusses how it transforms web browsing into immersive experiences.

What is WebXR

WebXR is a web API that supports augmented reality (AR) and virtual reality (VR) experiences directly through your web browsers. Think of it like watching a video or playing a game online, but instead, you’re inside a 3D world or interacting with virtual objects around you.

It lets developers create immersive applications that run on various devices, such as VR headsets and AR-capable smartphones, using standard web technologies like HTML, CSS, and JavaScript. Industry standards for WebXR, the WebXR Hit Test, and WebGL are used to render 3D graphics within these immersive environments.

Why Use WebXR

WebXR is boosting the digital content experience by merging the virtual and real worlds via web browsers. Here are the main reasons to use WebXR:

  • Low Barrier to Entry: With WebXR, users can access immersive experiences directly through their browsers, eliminating the need for specialized apps or hardware and making it more accessible to a wider audience. For example, before making a purchase, you could visit a shopping site and virtually try on clothes.
  • Ease of Content Creation: Developers can use familiar web technologies like HTML, CSS, and JavaScript, allowing for easier integration of XR content into existing web platforms. This means someone can build a fun game or interactive experience quickly without needing advanced programming skills. Think of simple online games that let you explore a 3D world.
  • Cross-Device Compatibility: WebXR supports a variety of devices, from VR headsets to AR-enabled smartphones, making sure experiences are available to users regardless of their hardware. For instance, users can explore a virtual museum or see AR art from their living room using their phone.
  • New Ways to Play and Interact: With WebXR, games and apps can be more engaging. For instance, imagine playing a treasure hunt game where you find virtual clues hidden in your real-world surroundings, making the experience more exciting.
  • Seamless Updates: Since everything is online, developers can modify and improve experiences quickly. For example, developers can add new features to a city’s virtual tour, and you can still access it instantly without having to download anything.
  • Community and Collaboration: WebXR lets developers share tools, libraries, and resources. For example, a group of creators can collaborate to build an interactive storytelling experience that blends with their unique styles.

Use Cases of WebXR

  • Gaming: WebXR facilitates immersive gaming experiences that blend with virtual and real environments. Gamers can explore 3D worlds, interact with characters, and engage in multiplayer scenarios directly through their browsers.
  • Education: In the education sector, WebXR faclitates interactive learning experiences. Students can embark on virtual field trips, learn complex concepts in 3D, and collaborate in real-time, to making learning more interactive.
  • Virtual Tours: WebXR enables virtual tours of museums, historical sites, or real estate properties. Users can explore these spaces as if physically present.
  • Training Simulations: Companies use WebXR for training purposes by creating realistic simulations that let employees practice skills in a safe environment. This can be applied in fields like healthcare, aviation, and manufacturing, improving retention and performance.
  • E-Commerce: WebXR enhances online shopping by allowing customers to visualize products in their own space. For example, before making purchasing a pierce of furniture, users can see it looks in their living room. This helps with better decision-making and improves customer satisfaction.
  • Social Interaction: WebXR can create social spaces for users to interact with friends or communities in virtual setups like virtual events, concerts, or shared 3D spaces to enhance the sense of presence and connection.

Browsers Compatible with WebXR

Many browsers are compatible with WebXR to meet the increasing demand for accessible virtual reality (VR) and augmented reality (AR) experiences.

By supporting this API, they drive cross-platform compatibility, and let developers create immersive applications that work seamlessly on various devices, like desktops and smartphones.

Here are some of the popular browsers that support WebXR:

1. Chrome

Chrome is one of the primary browsers that supports WebXR, via robust integration capabilities for both VR and AR experiences. Starting from version 79, Chrome provides extensive support for the WebXR API. Thereby, it allows developers to create immersive applications that utilize various VR headsets.

2. Edge

Built on Chromium, Microsoft Edge supports WebXR since version 79. This browser offers a smooth experience for users, accessing VR and AR content directly from the web, thereby leveraging the same WebXR capabilities as Chrome.

3. Opera

Opera also supports WebXR by utilizing its Chromium foundation. With support from version 58 onward, Opera drives immersive web experiences similar to those found in Chrome and Edge, making it suitable for VR and AR applications.

4. Samsung Internet

Samsung Internet, which is particularly optimized for Samsung mobile devices, supports WebXR from version 13.0. It focuses on delivering enhanced accessibility to AR experiences on mobile platforms.

5. Chrome for Android

Chrome for Android supports WebXR starting from version 79 and offers a mobile-friendly environment for VR and AR experiences. Users can access a wide range of immersive web applications, making it a good choice for on-the-go experiences.

6. Opera for Mobile

Opera for Mobile includes WebXR support, enabling users to experience VR and AR content directly from their mobile devices. While specific version details may vary, its Chromium base ensures compatibility with immersive web applications similar to its desktop counterpart.

As technology advances, updates to these browsers keep improving compatibility and performance for both developers and users.

How to Access the WebXR API

To access the WebXR API, you need a browser that supports WebXR and a device with VR or AR capabilities.

Here’s how to access the WebXR API

1. Check Compatibility:

Verify that your browser supports the WebXR API for AR/VR features.

Example:

if (navigator.xr) {

    console.log("WebXR is supported");

} else {

    console.log("WebXR is not supported. Please use a compatible browser.");

}

2. Initialize XR Session:

Call the requestSession method to start an immersive VR or AR session, specifying the desired mode as needed.

Example:

const startXR = async () => {

    try {

        const session = await navigator.xr.requestSession('immersive-vr'); // Change to 'immersive-ar' for AR

        console.log("XR Session started:", session);

        // Set up rendering context (canvas, WebGL, etc.)

        setupRendering(session);

    } catch (error) {

        console.error("Failed to start XR session:", error);

    }

};


document.getElementById('startButton').addEventListener('click', startXR);

3. Set Up Rendering Context:

Establish a rendering context using a <canvas> element with WebGL for visual output.

Example:

const setupRendering = (session) => {

    const canvas = document.createElement('canvas');

    const gl = canvas.getContext('webgl', { xrCompatible: true });

    document.body.appendChild(canvas);
   

    // Configure the canvas size based on the XR session

    session.addEventListener('end', () => {

        canvas.remove(); // Clean up when the session ends

    });
    

    // Begin rendering loop

    session.requestAnimationFrame(onXRFrame);

};

4. Establish a Rendering Loop:

Set up an ongoing loop to continuously update the scene and render frames, optimizing the handling of frame updates.

Example:

const onXRFrame = (time, frame) => {

    const session = frame.session;

    // Update your scene and rendering logic here



    // Request the next frame

    session.requestAnimationFrame(onXRFrame);

};

5. Manage User Input:

Capture user interactions, such as controller inputs, to enrich the immersive experience.

Example:

session.addEventListener('selectstart', (event) => {

    const controller = event.target; // Get the controller

    // Handle selection logic

});

How to Create and Start a WebXR Session

To effectively use the WebXR API, follow these expanded steps:

1. Create the Session

To initiate a WebXR session, use the navigator.xr.requestSession() method. This method takes parameters specifying the type of session (e.g., “immersive-vr” for virtual reality). Ensure the user’s device supports WebXR.

Example:

navigator.xr.requestSession('immersive-vr').then((session) => {

    // Handle session start

});

2. Customize the Session

You can customize the session by passing additional options to requestSession(). For instance, you can enable features like hand tracking or specify the session’s environment.

Example:

const options = {

    requiredFeatures: ['local-floor', 'hand-tracking']

};

navigator.xr.requestSession('immersive-vr', options).then((session) => {

    // Handle customized session

});

3. Prepare Session for Use

Before the session starts, set up necessary event listeners to handle session lifecycle events like end, visibilitychange, and select. This ensures your application responds correctly during the session.

Example:

session.addEventListener('end', onSessionEnded);

function onSessionEnded() {

    // Clean up resources

}

4. Prepare Session for Rendering

Once the session is active, create a render loop to update the scene and render frames. Use session.requestAnimationFrame() to synchronize rendering with the display refresh rate.

Example:

function render() {

    session.requestAnimationFrame(render);

    // Update and render scene here

}

render();

How to End the WebXR Session

Ending a WebXR session is a crucial aspect of managing augmented and virtual reality experiences. This process ensures that resources are released and the user’s environment returns to a normal state.

1. Shut Down the Session

To properly shut down a WebXR session, you can use the end() method of the XRSession interface. This method effectively ends the session and releases any associated resources.

Example:

if (xrSession) {

    xrSession.end().then(() => {

        console.log('Session ended successfully');

    }).catch((error) => {

        console.error('Error ending session:', error);

    });

}

In this example, the code verifies whether a session is currently active. If it is, it calls end(), logging a success message or an error if something goes wrong.

2. Identify When the Session Ends

Identifying when a WebXR session has ended can be done by listening for the ‘end’ event on the XRSession object. This enables developers to perform cleanup operations or update the UI once the session concludes.

Example:

xrSession.addEventListener('end', () => {

    console.log('The WebXR session has ended');

    // Additional code here

});

In this snippet, an event listener is added to the end event. This makes sure that any necessary actions can be taken when the session concludes.

What If Your System Is Not Compatible with WebXR

If your system lacks compatibility with WebXR, you can try alternative methods to enable XR experiences.

Two primary solutions are using a WebXR polyfill and employing an emulator.

1. WebXR Polyfill

A WebXR polyfill acts as a bridge, allowing browsers that don’t support WebXR to run XR applications by translating WebXR calls into equivalent methods. This can help you create a more consistent experience across various devices.

Example:

To use a WebXR polyfill, include this in your project:

<script src="https://cdn.rawgit.com/WebXR/Polyfill/master/dist/webxr-polyfill.js"></script>

Once included, you can utilize standard WebXR APIs, and the polyfill will handle compatibility issues in unsupported environments:

navigator.xr.requestSession('immersive-vr').then((session) => {

    // Start your XR experience here

});

2. Emulator Usage

Emulators simulate XR environments on non-compatible devices, allowing you to test and develop applications without needing physical hardware. This is useful for debugging and development.

Example:

For instance, you can use a web-based emulator like the WebXR Emulator in Chrome:

  1. Install the Chrome extension.
  2. Open your XR application in the browser.
  3. Activate the emulator and select a virtual device.

This setup lets you interact with your XR application as if you were using a compatible device, providing a valuable testing ground:

navigator.xr.isSessionSupported('immersive-vr').then((supported) => {

    if (supported) {

        console.log('Ready for XR!');

    } else {

        console.log('Using emulator instead');

    }

});

By leveraging a polyfill or an emulator, you can effectively extend the reach of your WebXR applications, even on incompatible systems.

However, emulators may not always be reliable when it comes to testing browser compatibility for WebXR applications. When that’s the case, you should rely on real-devices.

Talk to an Expert

Why Use Real Devices in Place of Emulators to Check Browser Compatibility of WebXR Applications

Testing on emulators can’t provide accurate results because it can’t simulate all user-specific conditions from the original device. Therefore, error-prone results can be delivered for the UX level testing.

Moreover, they are not reliable sources for performance testing. They can’t mimic the processor’s speed, battery usage, memory usage, and other performance-specific issues from the target device.

Moreover, they eliminate minor issues without reporting them.

Here are some reasons why you should use real devices when emulators don’t work reliably:

  • Real devices on the cloud provide accurate UX-level testing results for actions like sch s swipe, zoom, scroll, push notifications, phone calls, Bluetooth, etc.
  • Real devices are reliable sources for performance testing as they deliver accurate results.
  • You can observe your apps’ in-depth performance with real-device testing. Every step of your app’s behavior will be shown to you.
  • Emulators can’t simulate a device’s GPS, network, and time zones. However, real devices replicate them and drive Geolocation testing and localization testing.

BrowserStack Live Banner

Conclusion

In conclusion, developing WebXR opens up exciting opportunities for immersive experiences across devices. However, ensuring compatibility can be challenging due to varying browser and hardware support. To mitigate these issues, leveraging polyfills and emulators can provide temporary solutions.

For a comprehensive testing approach, consider using BrowserStack. This platform provides capabilities for real-device and cross-browser testing, allowing you to test your WebXR applications on real devices and multiple browser combinations, ensuring optimal performance and compatibility.

With BrowserStack, you can validate your applications in real-world scenarios, giving you confidence in delivering seamless XR experiences to your users.

Try BrowserStack for Free

Tags
Visual Testing

Featured Articles

Browser Compatibility for VueJS Web Apps

Browser compatibility with CSS Gradients

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers