The lock()
property of the ScreenOrientation
interface locks the orientation of the containing document to the specified orientation.
Typically orientation locking is only enabled on mobile devices, and when the browser context is full screen. If locking is supported, then it must work for all the parameter values listed below.
A Promise
that resolves after locking succeeds.
The promise may be rejected with the following exceptions:
-
NotSupportedError
DOMException
-
The user agent does not support locking the screen orientation.
-
SecurityError
DOMException
-
The user-agent's pre-lock conditions are not met. For example, a browser may require that the top-level browsing context's Document
is full screen. The promise may also be rejected with this error if the document has the sandboxed orientation lock browsing context flag set.
TypeError
-
The orientation
argument was not supplied.
This example shows how to lock the screen to the opposite orientation of the current one. Note that this example will only work on mobile devices and other devices that support orientation changes.
<div id="example_container">
<button id="fullscreen_button">Fullscreen</button>
<button id="lock_button">Lock</button>
<button id="unlock_button">Unlock</button>
<textarea id="log" rows="7" cols="85"></textarea>
</div>
const log = document.getElementById("log");
const rotate_btn = document.querySelector("#lock_button");
rotate_btn.addEventListener("click", () => {
log.textContent += `Lock pressed \n`;
const oppositeOrientation = screen.orientation.type.startsWith("portrait")
? "landscape"
: "portrait";
screen.orientation
.lock(oppositeOrientation)
.then(() => {
log.textContent = `Locked to ${oppositeOrientation}\n`;
})
.catch((error) => {
log.textContent += `${error}\n`;
});
});
const unlock_btn = document.querySelector("#unlock_button");
unlock_btn.addEventListener("click", () => {
log.textContent += "Unlock pressed \n";
screen.orientation.unlock();
});
const fullscreen_btn = document.querySelector("#fullscreen_button");
fullscreen_btn.addEventListener("click", () => {
log.textContent += "Fullscreen pressed \n";
const container = document.querySelector("#example_container");
container.requestFullscreen().catch((error) => {
log.textContent += `${error}\n`;
});
});
To test the example, first press the Fullscreen button. Once the example is full screen, press the Lock button to switch the orientation, and Unlock to return to the natural orientation.