JavaScript Screen Orientation API: Detect and Lock

The Screen Orientation API provides web developers with programmatic access to the orientation of a user’s display. This article covers the essentials of the Screen Orientation API, explaining how to read the current viewport orientation, listen dynamically for orientation change events, and lock or unlock the screen orientation using JavaScript.

What is the Screen Orientation API?

The Screen Orientation API gives web applications the ability to read the screen’s current layout state and lock the screen to a specific orientation. Available through the screen.orientation object, this modern standard replaces older, non-standard approaches like window.orientation and provides a promise-based mechanism for managing layout behaviour, especially on mobile devices.

Detecting Current Viewport Orientation

To read the current orientation state, inspect the properties of the screen.orientation object:

const orientationType = screen.orientation.type;
const orientationAngle = screen.orientation.angle;

console.log(`Type: ${orientationType}`);
console.log(`Angle: ${orientationAngle} degrees`);

Listening for Orientation Changes

You can track orientation changes in real time by attaching an event listener to the screen.orientation object using the change event:

screen.orientation.addEventListener("change", () => {
    console.log(`Orientation changed to: ${screen.orientation.type}`);
    console.log(`Current angle: ${screen.orientation.angle}`);
});

Alternatively, you can assign a handler function to the onchange property:

screen.orientation.onchange = () => {
    console.log(`Updated orientation: ${screen.orientation.type}`);
};

Locking the Screen Orientation

The lock() method locks the viewport to a specific orientation. It takes a string argument specifying the target orientation and returns a Promise.

Allowed lock types include: * "any" * "natural" * "landscape" * "portrait" * "portrait-primary" * "portrait-secondary" * "landscape-primary" * "landscape-secondary"

Requirements for Locking Orientation

Browsers impose security and usability restrictions on orientation locking: 1. The application usually must be running in fullscreen mode (via the Fullscreen API) or installed as a Progressive Web App (PWA). 2. The request must be initiated by a user interaction, such as a click or tap event.

async function lockToLandscape() {
    try {
        // Request fullscreen first if required by the browser
        if (document.documentElement.requestFullscreen) {
            await document.documentElement.requestFullscreen();
        }
        
        // Lock the orientation to landscape
        await screen.orientation.lock("landscape");
        console.log("Screen orientation locked to landscape.");
    } catch (error) {
        console.error("Failed to lock orientation:", error);
    }
}

Unlocking the Screen Orientation

To release a previously applied orientation lock and allow the screen to rotate freely with the device, call the unlock() method:

function releaseOrientationLock() {
    screen.orientation.unlock();
    console.log("Screen orientation lock removed.");
}

Feature Detection and Error Handling

Always verify browser support before accessing the API and wrap lock attempts in try...catch blocks to handle unsupported platforms or rejected permissions:

if ("orientation" in screen && "lock" in screen.orientation) {
    // API is fully supported
} else {
    console.warn("Screen Orientation API is not supported on this device/browser.");
}