The Screen Orientation API W3C Working Draft 22 May 2012 This version: http://www.w3.org/TR/2012/WD-screen-orientation-20120522/ Latest published version: http://www.w3.org/TR/screen-orientation/ Latest editor's draft: http://dvcs.w3.org/hg/screen-orientation/raw-file/tip/Overview.html Editor: Mounir Lamouri , Mozilla Copyright © 2012 W3C ® ( MIT , ERCIM , Keio ), All Rights Reserved. W3C liability , trademark and document use rules apply. Abstract The Screen Orientation API's goal is to provide an interface for web applications to be able provides the ability to read the screen orientation state, type and angle, to be informed when this the screen orientation state changes changes, and to be able to lock the screen orientation to a specific state.

Status of This Document

This section describes the status of this document is still in a work in progress state. You can have a look 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 opened issues . If you see any problem that is not in that list, feel free to discuss it in the W3C technical reports index mailing list at http://www.w3.org/TR/. or file an issue .

This document was published by the Web Applications Working Group as a First Public Working Draft. This document is intended specification defines conformance criteria that apply to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webapps@w3.org ( subscribe , archives ) with [screen-orient] at single product: the start of user agent that implements the subject header. All feedback is welcome. interfaces that it contains.

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 Implementations that use ECMAScript to cite expose the APIs defined in this document as other than work specification MUST implement them in progress. This document was produced by a group operating under the 5 February 2004 W3C Patent Policy . W3C maintains a public list of any patent disclosures made in connection manner consistent 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 ECMAScript Bindings defined in accordance with section 6 of the W3C Patent Policy . Web IDL specification [[!WEBIDL]].

Table of Contents

Dependencies

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

1. Introduction

This section is non-normative. Promise objects are defined in [[!ECMASCRIPT]].

The Screen Orientation API provides an interface for web applications to access and lock the user's device's screen orientation state. fullscreen element is defined in [[!FULLSCREEN]].

This examples now visible algorithm is an application that shows the current screen orientation to the user every time the screen orientation state changes: defined in [[!PAGE-VISIBILITY]].

<!DOCTYPE html> <html> <script> function show() { alert("Screen orientation state is " + screen.orientation); }

screen.addEventListener("orientationchange", show, false); show(); </script> </html> animation frame task is not defined but used in [[!FULLSCREEN]].

This should be updated when animation frame task gets defined.

2. Conformance Interface definitions

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this

Extensions to the Screen interface

The CSSOM View specification are non-normative. Everything else in defines a Screen interface [[!CSSOM-VIEW]], which this specification is normative. extends:

          partial interface Screen {
            readonly attribute ScreenOrientation orientation;
          };
        

The key words must , must not , required , should , should not , recommended , may , and optional in this specification are to be interpreted as described in [ RFC2119 orientation ]. object is an instance of ScreenOrientation , which is described below.

ScreenOrientation interface


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

This specification defines conformance criteria that apply to a single product: When the lock () method is invoked, the user agent that implements MUST run the interfaces that it contains. apply an orientation lock steps to the responsible document using orientation .

Implementations that use ECMAScript When the unlock () method is invoked, the user agent MUST run the steps to expose lock the APIs defined in this specification must implement them in a manner consistent with orientation of the ECMAScript Bindings defined in responsible document to the Web IDL specification [ WEBIDL responsible document ]. 's default orientation .

3. Terminology The

Function unlock() interface represents does not return a function in Promise because it is equivalent to locking to the scripting language being used as defined in [ HTML5 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.

The concepts queue a task When getting the type and fire a simple event attribute, the user agent MUST return the responsible document 's current orientation type .

When getting the angle are defined in [ HTML5 attribute, the user agent ]. MUST return the responsible document 's current orientation angle .

The terms event handlers onchange and attribute is an event handler whose corresponding event types handler event type is change .

OrientationType enum


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

OrientationLockType enum


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

Concepts

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

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

Reading the screen orientation

The concepts of browsing context All documents have a current orientation type and active 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 defined 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 [ HTML5 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.

3.1 orientation.angle and orientation.type relationship Current

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 current steps to update the orientation information should be an orientation amongst those values: 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 portrait-primary , landscape-secondary .
  2. Otherwise, if the orientation screen width is in less than or equal to the primary portrait mode; screen height, set the document 's current orientation type to portrait-primary or portrait-secondary , if .
  3. Set the document 's current orientation is angle to the clockwise angle in degrees between the secondary portrait mode; landscape-primary , if 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 in the primary landscape mode; landscape-secondary , if opposite of the orientation physical rotation. In other words, if a device is in turned 90 degrees on the secondary landscape mode. right, the current orientation angle would be 270 degrees.

The notion of primary and secondary depends 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 platform. Usually, platforms have current orientation angle relation consistent for any given document .

Locking the screen orientation

The user agent MAY require a way document and its associated browsing context to distinguish meet one or more security conditions in order to be able to lock the two portrait and landscape orientations. screen orientation. For example, on most phones, portrait-primary is going 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 that is used when if the phone is in hand and secondary will platform conventions do not expect applications to be upside-down able to change the screen orientation. Also, landscape-primary will 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 landscape 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 90 degree document using orientation counter-clock 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 secondary abort these steps.
  2. The following sub-steps MAY be run asynchronously for performance reasons, for example, if the other one. On tablets, landscape-primary will user agent has browsing contexts living in different processes:
    1. Let browsing contexts be the orientation used when list of the tablet descendant browsing contexts of the top-level browsing context 's document .
    2. If one of the browsing contexts 's document 's pending promise is in hands. 3.2 Allowed orientations The allowed orientations should not null :
      1. Let doc be orientations amongst the current orientation document list or amongst those values: which has a not null pending promise .
      2. Reject doc 's pending promise with portrait , value that covers DOMException whose name is portrait-primary AbortError .
      3. Set doc 's pending promise to null and .
  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 portrait-secondary DOMException cases; whose name is SecurityError and abort these steps.
  4. Let orientations be an empty list.
  5. Depending on orientation value, do the following:
    landscape , value that covers portrait-primary or portrait-secondary or landscape-primary and or landscape-secondary cases; 4. Extensions
    Append orientation to the orientations .
    Screen landscape Interface The CSSOM View specification defines a
    Depending on platform convention, append Screen interface [ landscape-primary , or landscape-secondary , or both to orientations .
    CSSOM-VIEW ], which this specification extends: <span class="idlInterface" id= "idl-def-Screen">partial interface <span class= "idlInterfaceID">Screen { readonly attribute <span class= "idlAttrType"> <span class= "idlAttrName"><a href= "#widl-Screen-orientation">orientation <span class= "idlMethType"> <span class= "idlMethName"><a href= "#widl-Screen-lockOrientation-boolean-DOMtring-orientation">lockOrientation <span class= "idlMethType"> <span class= "idlMethName"><a href= "#widl-Screen-unlockOrientation-void">unlockOrientation [<span class= "extAttr">TreatNonCallableAsNull] attribute <span class= "idlAttrType"> <span class= "idlAttrName"><a href= "#widl-Screen-onorientationchange">onorientationchange }; portrait 4.1 Attributes onorientationchange of type Function , nullable
    Depending on platform convention, append portrait-primary , or portrait-secondary , or both to orientations .
    orientation natural of type
    Append portrait-primary or landscape-primary to orientations such as the associated DOMString current orientation angle is 0.
    any , readonly
    The user agent must return Append portrait-primary , portrait-secondary , landscape-primary and landscape-secondary to orientations .
  6. Set pending-promise to be a newly-created Promise .
  7. Return pending-promise and continue asynchronously.
  8. Lock the value orientation of the document to orientations .
  9. If locking the orientation did not result in a change of orientation, as part of the output device. The returned next animation frame task , resolve pending-promise with undefined and set pending-promise to null .
If locking the orientation must results in an orientation change, the promise will be resolved when the orientation will change as described in the current Handling screen orientation changes list. section.
4.2 Methods lockOrientation The

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

  1. Set the document 's orientation lock to orientations .
  2. If the active orientation isn't part of lock is not the allowed orientations document 's orientation lock , abort these steps.
  3. If the method must return false. active orientation lock value is equal to orientations value, abort these steps.
  4. If locking 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 isn't currently allowed, .
    3. After the method must return false. change has happened, prevent the document 's top-level browsing context 's screen orientation from changing until those steps are run again.
    4. Otherwise, Abort these steps.
  5. If the method must return true and 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 should type. However, it has to be locked 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.
When

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 done, 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 document s is focused, the active orientation did change, 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 fire MUST run the steps to lock the orientation of the document to the document 's orientation lock .

Whenever a simple event top-level browsing context named orientationnchange at is navigated , the user agent MUST lock the Screen object. Parameter Type Nullable Optional Description orientation of the document to the document 's default orientation .

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 DOMtring pending promise with undefined .
      2. Set doc 's pending promise to null ✘ ✘ Return type: .
    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.
  3. boolean Fire a simple event named change at doc 's unlockOrientation screen.orientation object.

The Whenever a document becomes visible per [[!PAGE-VISIBILITY]], in other words after the now visible algorithm is run, the user agent must disable MUST run the current lock applied on following substeps as part of the screen with lockOrientation . If next animation frame task :

  1. Let type and angle be respectively the document 's current browsing context orientation type has a default orientation, the screen and current orientation should revert to that. No parameters. Return type: angle .
  2. void Update the orientation information When of the screen document .
  3. If type is different from the document 's current orientation changes in type or angle from the document 's current browsing context orientation angle , run the user agent following sub-steps:
    1. If the document must queue '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 which updates the MUST be annotated with process user orientation change attribute and fire when running the next step.
    3. Fire a simple event named orientationchange change at the document 's Screen 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 .

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

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

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 landscape-primary any .

Interactions with other specifications

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

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 application B a screen orientation lock is locked applied, the user agent MUST lock the orientation of the document to the document 's default orientation .

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

Interaction with DeviceOrientation

The DeviceOrientation specification [[DEVICE-ORIENTATION]] defines a portrait-primary , switching from application A deviceorientation event that can be used to B or B 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 will not fire basic example being a compass application. Another example would be an orientationchange event because both application will keep giving direction to the orientation they had. user or an augmented reality game pointing to an objective.

However, locking Drawing on the application 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 fire apply an orientation lock to a document using orientationchange natural if to make that assumption a certitude. Otherwise, reading the application wasn't in document 's current orientation angle via screen.orientation.angle and listening to the specified type before being locked. change event can help the developer to compensate the screen orientation angle.

5. Event handlers Interaction with Web Application Manifest

The following are Web Application Manifest specification [[appmanifest]] allows web applications to set the event handlers (and their corresponding event handler event types document ) that must be supported as attributes by 's default orientation .

Interaction with CSS Device Adaptation

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

event handler event handler event type

Examples

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


<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>

onorientationchange

<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.


<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.


<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();
        }

orientationchange

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

A. Acknowledgements

Acknowledgments

Many thanks

Thanks to Jonas Sicking 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 specification. B. References B.1 Normative references [CSSOM-VIEW] Anne van Kesteren. CSSOM View Module. 22 February 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-cssom-view-20080222 [HTML5] Ian Hickson; David Hyatt. HTML5. 25 May 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/html5 [RFC2119] S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt [WEBIDL] Cameron McCormack. Web IDL. 27 September 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2011/WD-WebIDL-20110927/ B.2 Informative references No informative references. API.