The Screen Orientation API

W3C Working Draft

This version:
https://www.w3.org/TR/2018/WD-screen-orientation-20180706/
Latest published version:
https://www.w3.org/TR/screen-orientation/
Latest editor's draft:
https://w3c.github.io/screen-orientation/
Test suite:
https://github.com/web-platform-tests/wpt/tree/master/screen-orientation
Previous version:
https://www.w3.org/TR/2018/WD-screen-orientation-20180601/
Editors:
Mounir Lamouri (Google Inc.)
Marcos Cáceres (Mozilla)
Participate:
We are on Github.
File a bug.
Commit history.
Mailing list.

Abstract

The Screen Orientation API provides the ability to read the screen orientation type and angle, to be informed when the screen orientation state changes, and be able to lock the screen orientation to a specific state.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document is still in a work in progress state. You can have a look at the opened issues. If you see any problem that is not in that list, feel free to discuss it in the mailing list or file an issue .

This document was published by the Web Platform Working Group as a Working Draft. This document is intended to become a W3C Recommendation. Comments regarding this document are welcome. Please send them to public-webapps@w3.org (subscribe, archives).

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 February 2018 W3C Process Document.

1. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MAY, MUST, and SHOULD are to be interpreted as described in [RFC2119].

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Implementations that use ECMAScript to expose the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL].

2. Dependencies

The following concepts and interfaces are defined in [HTML]:

fullscreen element is defined in [FULLSCREEN].

now visible algorithm is defined in [PAGE-VISIBILITY].

fire an event is defined in [DOM].

animation frame task is not defined but used in [FULLSCREEN].

Issue 1
This should be updated when animation frame task gets defined.

3. Interface definitions

3.1 Extensions to the Screen interface

The CSSOM View specification defines a Screen interface [CSSOM-VIEW], which this specification extends:
partial interface Screen {
  [SameObject] readonly attribute ScreenOrientation orientation;
};

The orientation object is an instance of ScreenOrientation, which is described below.

3.2 ScreenOrientation interface

[Exposed=Window]
interface ScreenOrientation : EventTarget {
  Promise<void> lock(OrientationLockType orientation);
  void unlock();
  readonly attribute OrientationType type;
  readonly attribute unsigned short angle;
  attribute EventHandler onchange;
};

When the lock() method is invoked, the user agent MUST run the apply an orientation lock steps to the responsible document using orientation.

When the unlock() method is invoked, the user agent MUST run the steps to lock the orientation of the responsible document to the responsible document's default orientation.

Note

unlock() does not return a promise because it is equivalent to locking to the default orientation which might or might not be known by the user agent. Hence, the user agent can not predict what the new orientation is going to be and even if it is going to change at all.

When getting the type attribute, the user agent MUST return the responsible document's current orientation type.

When getting the angle attribute, the user agent MUST return the responsible document's current orientation angle.

Note

angle indicates how far the user has turned the device counterclockwise from the natural orientation. When the device is rotated 90° counterclockwise, the screen compensates by rotating 90° clockwise, so angle returns 90.

If the device is rotated 90° clockwise from its natural orientation, the screen compensates by rotating 90° counterclockwise, so angle returns 270.

The value returned by this property is always in the range 0-359. It never returns negative values.

The onchange attribute is an event handler whose corresponding event handler event type is "change".

3.3 OrientationType enum

enum OrientationType {
  "portrait-primary",
  "portrait-secondary",
  "landscape-primary",
  "landscape-secondary"
};

3.4 OrientationLockType enum

enum OrientationLockType {
  "any",
  "natural",
  "landscape",
  "portrait",
  "portrait-primary",
  "portrait-secondary",
  "landscape-primary",
  "landscape-secondary"
};

4. Concepts

The term screen is equivalent to the screen of the output device associated to the Window, as per [CSSOM-VIEW].

Algorithms defined in this specification assume that for each document there is a pending promise, which is initially set to null, which is a promise whose associated operation is to lock the screen orientation.

4.1 Reading the screen orientation

All documents have a current orientation type and a current orientation angle. Both of them SHOULD be initialized when the document is created, otherwise they MUST be initialized the first time they are accessed and before their value is read. The user agent MUST update the orientation information of the document to initialize them.

For a given document, the current orientation type and the current orientation angle are strongly linked in the sense that for any given type, there will be a specific angle associated. However, the user agent can associate *-primary and *-secondary values at will. For example, if 90 is associated with landscape-primary and 270 with landscape-secondary for one document , another one MAY get the opposite relationship.

Best Practice 1: orientation.angle and orientation.type relationship

Never assume any cross-devices relationship between the screen orientation type and the screen orientation angle. Any assumption would be wrong given that a device might have 90 and 270 as the angles for landscape types but another device will have 0 and 180, depending on its natural orientation. Instead, it is recommended to check during runtime the relationship between angle and type.

The steps to update the orientation information of a document are as follows:

  1. If the screen width is greater than the screen height, set the document's current orientation type to landscape-primary or landscape-secondary.
  2. Otherwise, if the screen width is less than or equal to the screen height, set the document's current orientation type to portrait-primary or portrait-secondary.
  3. Set the document's current orientation angle to the clockwise angle in degrees between the orientation of the viewport as it is drawn and the natural orientation of the device (i.e., the top of the physical screen). This is the opposite of the physical rotation. In other words, if a device is turned 90 degrees on the right, the current orientation angle would be 270 degrees.

The decision whether the document's current orientation type should be set to *-primary or *-secondary is up to the user agent. For example, it can be based on the device preferred angles, the user's preferred orientations or the current orientation when the application starts. However, a user agent MUST keep the current orientation type and the current orientation angle relation consistent for any given document.

4.2 Locking the screen orientation

The user agent MAY require a document and its associated browsing context to meet one or more security conditions in order to be able to lock the screen orientation. For example, a user agent might require a document's top-level browsing context to be fullscreen (see Interaction with Fullscreen API) in order to allow an orientation lock.

The user agent MAY reject all attempts to lock the screen orientation if the platform conventions do not expect applications to be able to change the screen orientation. For example, on most desktop platforms, applications can not change the screen orientation.

If the user agent supports locking the screen orientation, it MUST allow the screen to be locked to all of the states of the OrientationLockType enum.

A document's orientation lock is the orientation lock that applies on its top-level browsing context. An orientation lock is an unordered set of OrientationType.

The steps to apply an orientation lock to a document using orientation are as follows:

  1. If the user agent does not support locking the screen orientation, return a promise rejected with a DOMException whose name is NotSupportedError and abort these steps.
  2. The following sub-steps MAY be run asynchronously for performance reasons, for example, if the user agent has browsing contexts living in different processes:
    1. Let browsing contexts be the list of the descendant browsing contexts of the top-level browsing context's document.
    2. If one of the browsing contexts's document's pending promise is not null:
      1. Let doc be the document which has a not null pending promise.
      2. Reject doc's pending promise with DOMException whose name is AbortError.
      3. Set doc's pending promise to null .
  3. If the document's active sandboxing flag set has the sandboxed orientation lock browsing context flag set, or user agent doesn't meet the security conditions to perform an orientation change, return a promise rejected with a DOMException whose name is SecurityError and abort these steps.
  4. Let orientations be an empty list.
  5. Depending on orientation value, do the following:
    portrait-primary or portrait-secondary or landscape-primary or landscape-secondary
    Append orientation to orientations.
    landscape
    Depending on platform convention, append landscape-primary, or landscape-secondary, or both to orientations.
    portrait
    Depending on platform convention, append portrait-primary, or portrait-secondary, or both to orientations.
    natural
    Append portrait-primary or landscape-primary to orientations such as the associated current orientation angle is 0.
    any
    Append portrait-primary, portrait-secondary, landscape-primary and landscape-secondary to orientations.
  6. Set doc's pending promise to a newly-created promise.
  7. Return doc's pending promise and continue asynchronously.
  8. Lock the orientation of the document to orientations.
  9. If locking the orientation did not result in a change of orientation, as part of the next animation frame task, resolve pending-promise with undefined and set pending-promise to null.
Note
If locking the orientation results in an orientation change, the promise will be resolved when the orientation will change as described in the Handling screen orientation changes section.

When the user agent has to lock the orientation of a document to orientations, it MUST run the following steps:

  1. Set the document's orientation lock to orientations.
  2. If the active orientation lock is not the document's orientation lock, abort these steps.
  3. If the active orientation lock value is equal to orientations value, abort these steps.
  4. If orientations contains only one value, run the following sub-steps:
    1. Let orientation be the value contained in orientations.
    2. Change how the viewport is drawn so that the document's current orientation type will be equal to orientation.
    3. After the change has happened, prevent the document's top-level browsing context's screen orientation from changing until those steps are run again.
    4. Abort these steps.
  5. If the document's current orientation type is not part of orientations, change how the viewport is drawn such as the document's current orientation type will be equal to one of orientations' values.
  6. Otherwise, depending on platform conventions, change how the viewport is drawn in order to make it match another screen orientation type. However, it has to be part of orientations.
  7. Allow the user to change the screen orientation to any value part of orientations and only those values until those steps are run again. The method to define the current screen orientation has to match the platform conventions.

4.3 Screen orientation lock lifetime

To determine the active orientation lock, the user agent MUST run the following steps:

  1. If there is only one top-level browsing context with a document that is visible per [PAGE-VISIBILITY], the active orientation lock is the document's orientation lock.
  2. Otherwise, if there are more than one top-level browsing context with a document that is visible per [PAGE-VISIBILITY] but only one of those documents is focused, the active orientation lock is the focused document's orientation lock.
  3. Otherwise, the active orientation lock SHOULD be the latest focused document's orientation lock, unless stated otherwise by the platform conventions.

Whenever the active orientation lock changes, the user agent MUST run the steps to lock the orientation of the document to the document's orientation lock.

Whenever a top-level browsing context is navigated, the user agent MUST lock the orientation of the document to the document's default orientation.

4.4 Handling screen orientation changes

Whenever the viewport's angle changes, the user agent MUST run the following steps as part of the next animation frame task:

  1. Let browsing contexts be the list of the descendant browsing contexts of the top-level browsing context's document.
  2. For each browsing context in browsing contexts, run the following sub-steps:
    1. Let doc be the browsing context's active document.
    2. If doc is not visible per [PAGE-VISIBILITY], abort these steps.
    3. Update the orientation information of doc.
    4. If doc's pending promise is not null:
      1. Resolve doc's pending promise with undefined.
      2. Set doc's pending promise to null .
    5. If the orientation change was triggered by a user gesture such as the user turning the device, as opposed to a call to lock, the task MUST be annotated with process user orientation change when running the next step.
    6. Fire an event named change at doc 's screen.orientation object.

Whenever a document becomes visible per [PAGE-VISIBILITY], in other words after the now visible algorithm is run, the user agent MUST run the following substeps as part of the next animation frame task:

  1. Let type and angle be respectively the document's current orientation type and current orientation angle.
  2. Update the orientation information of the document.
  3. If type is different from the document's current orientation type or angle from the document 's current orientation angle, run the following sub-steps:
    1. If the document's pending promise is not null:
      1. Resolve the document's pending promise with undefined.
      2. Set the document's pending promise to null.
    2. If the orientation change was triggered by a user gesture such as the user turning the device, as opposed to a call to lock, the task MUST be annotated with process user orientation change when running the next step.
    3. Fire an event named change at the document's screen.orientation object.

An algorithm is triggered by a user generated orientation change if the task in which the algorithm is running is annotated with process user orientation change.

Note

Developers need to be aware that a screen.orientation object from a document that is not visible, as per [PAGE-VISIBILITY], will not receive an orientation change event. This is to prevent unnecessary changes to layout, etc. in the non-visible web application.

Issue 2
This section could be improved if the [PAGE-VISIBILITY] specification had a hook for when the document becomes visible and hidden. issue 77.

4.5 Default orientation

A document's default orientation is the set of orientations to which the screen orientation is locked when it is not explicitly locked by this API or any other means.

For the perspective of a document, locking to the default orientation is equivalent to unlocking because it means that it no longer has a lock applied. However, it does not mean that the default orientation has to be any.

5. Interactions with other specifications

This section explains how this specification interacts with other related specifications of the platform.

5.1 Interaction with Fullscreen API

As a security condition, a user agent MAY restrict locking the screen orientation exclusively to when the top-level browsing context's document's fullscreen element is not null. When that security condition applies, whenever the document's fullscreen element is empty and a screen orientation lock is applied, the user agent MUST lock the orientation of the document to the document's default orientation.

Issue 3
This section could be improved if the [FULLSCREEN] specification had a hook for when the document is no longer fullscreen. See issue 62 .

5.2 Interaction with DeviceOrientation

This section is non-normative.

The DeviceOrientation specification [DEVICE-ORIENTATION] defines a deviceorientation event that can be used to discover the physical orientation of the device. Such event can be used to draw things on the screen that could point to a specific direction. A basic example being a compass application. Another example would be an application giving direction to the user or an augmented reality game pointing to an objective.

Drawing on the screen in order to point to a physical location requires to know the device orientation and the orientation of the screen in the device coordinates. Without the APIs defined in this specification, a developer has to assume that the document's current orientation angle is 0. With the help of the APIs described in this specification, the developer can apply an orientation lock to a document using natural to make that assumption a certitude. Otherwise, reading the document's current orientation angle via screen.orientation.angle and listening to the "change" event can help the developer to compensate the screen orientation angle.

5.3 Interaction with Web Application Manifest

This section is non-normative.

The Web Application Manifest specification [appmanifest] allows web applications to set the document's default orientation.

5.4 Interaction with CSS Device Adaptation

This section is non-normative.

The CSS Device Adaptation specification [CSS-ADAPTATION] defines, independently of this document, a way to lock the screen orientation for a web page using CSS.

6. Examples

This section is non-normative.

This example shows the current screen orientation to the console every time the screen orientation state changes.

Example 1
<script>
  var show = function() {
     console.log("Orientation type is " + screen.orientation.type);
     console.log("Orientation angle is " + screen.orientation.angle);
  }

  screen.orientation.addEventListener("change", show);
  window.onload = show;
</script>

<button onclick='screen.orientation.unlock()'>
  Unlock
</button>
<button onclick="screen.orientation.lock('portrait')">
  Lock to portrait
</button>
<button onclick="screen.orientation.lock('landscape')">
  Lock to landscape
</button>

This example waits to be fullscreen before locking the screen orientation and starting.

Example 2
<script>
  var start = function() {
    document.onfullscreenchange = function() {
      screen.orientation.lock('natural').then(startInternal);
    }
    document.documentElement.requestFullscreen();
  }
</script>
<button onclick='start();'>
  Start
</button>

This example asks the user to manually rotate the device if the Screen Orientation API is not available.

Example 3
<script>
  var start = function() {
    screen.orientation.lock('landscape-primary').then(
      startInternal,
      function() {
        alert('To start, rotate your screen to landscape.');

        var orientationChangeHandler = function() {
          if (!screen.orientation.type.startsWith('landscape')) {
            return;
          }
          screen.orientation.removeEventListener('change', orientationChangeHandler);
          startInternal();
        }

        screen.orientation.addEventListener('change', orientationChangeHandler);
      });
  }
  window.onload = start;
</script>

A. Acknowledgments

Thanks to Marcos Cáceres, Christophe Dumez, Anne van Kesteren and Chundong Wang for their useful comments.

Special thanks to Chris Jones and Jonas Sicking for their contributions to the initial design of this API.

B. References

B.1 Normative references

[CSSOM-VIEW]
CSSOM View Module. Simon Pieters. W3C. 17 March 2016. W3C Working Draft. URL: https://www.w3.org/TR/cssom-view-1/
[DOM]
DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
[FULLSCREEN]
Fullscreen API Standard. Philip Jägenstedt. WHATWG. Living Standard. URL: https://fullscreen.spec.whatwg.org/
[HTML]
HTML Standard. Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[PAGE-VISIBILITY]
Page Visibility (Second Edition). Jatinder Mann; Arvind Jain. W3C. 29 October 2013. W3C Recommendation. URL: https://www.w3.org/TR/page-visibility/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WEBIDL]
Web IDL. Cameron McCormack; Boris Zbarsky; Tobie Langel. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/

B.2 Informative references

[appmanifest]
Web App Manifest. Marcos Caceres; Kenneth Christiansen; Mounir Lamouri; Anssi Kostiainen; Rob Dolin; Matt Giuca. W3C. 4 July 2018. W3C Working Draft. URL: https://www.w3.org/TR/appmanifest/
[CSS-ADAPTATION]
CSS Device Adaptation Module Level 1. Rune Lillesveen; Florian Rivoal; Matt Rakow. W3C. 29 March 2016. W3C Working Draft. URL: https://www.w3.org/TR/css-device-adapt-1/
[DEVICE-ORIENTATION]
DeviceOrientation Event Specification. Rich Tibbett; Tim Volodine; Stephen Block; Andrei Popescu. W3C. 30 May 2017. W3C Note. URL: https://www.w3.org/TR/orientation-event/