A shim for window.orientation based on window.screen.orientation

05 May 2014

Last week I wrote a Firefox for Android add-on that shims support for the non-standard window.orientation property, mapping to the values returned by the Screen Orientation API (which are currently prefixed in Gecko as screen.mozOrientation).

In a nutshell, it's pretty simple:

const orientationMap = {
  "portrait-primary": 0,
  "portrait-secondary": 180,
  "landscape-primary": 90,
  "landscape-secondary": -90

window["orientation"] = orientationMap[window.screen.mozOrientation]

You just need to worry about writing adding the orientation property before any other JS runs and take care to call orientationchange handlers, dispatch events, etc.

I've only got two manual tests at http://miketaylr.github.io/orientation-shim/ so it's probably loaded with bugs—but a few quick tests on sites like http://newyork.schmap.com/ seem promising.

(Sadly I couldn't find any window.orientation tests in the Android or WebKit projects (probably becuase I'm lousy at binging things?)).

You can grab the .xpi (or build it, whatever) and give it a spin if you're into that. For a limited time I'm taking bug reports at no charge to you.


Rich Tibbett writes (1 & 2):

"Nice post but I don't think it's that simple. Lots of tablets are [landscape-primary] yet window.orientation == 0. Any relationship between orientation angle and portrait/landscape is coincidental. That's why we need the orientation angle."

So perhaps I have more work to to.