Locking screen orientation on Android

Chrome 28 and higher now supports setting the orientation in your app. Simply do the following:

 screen.orientation.lock("landscape")
 screen.orientation.lock("portrait")

The screen will then shift to the orientation you specify and ignore the actual orientation of the device.

This only works on Chrome. If you try to execute this code on an iPhone, it will get an error and the orientation will not be affected. To improve the code above so it runs without errors, do the following:

If screen.orientation <> undefined Then
  screen.orientation.lock("landscape")
End If

The screen orientation still won’t change on an iPhone, but at least there won’t be an error!