This version of the cordova-plugin-screen-orientation plugin adds a native listener to get the device's current orientation, even when it's locked via orientation.lock(). It works on both Android and iOS.
Define window.onRotationUpdate, take in both rotation integer (0, 90, -90, 180), and device auto rotate locked boolean (true, false), as shown in the example below:
window.onRotationUpdate = function(rotation, locked) {
}
Congratulations! You can now detect when the device itself has changed orientation, even when your cordova activity is locked in portrait/landscape mode.
This plugin also disables the portrait upsidedown orientation on iOS when it is unlocked using orientation.unlock(), because why would you want that?
Important: This version of the plugin removes rotation locking and unlocking on iOS 16 and above. This is because I'm using a custom solution for these newer versions. You should use this version of the plugin, not the master branch.
Cordova plugin to set/lock the screen orientation in a common way for iOS, Android, and windows-uwp. This plugin is based on Screen Orientation API so the api matches the current spec.
The plugin adds the following to the screen object (window.screen
):
// lock the device orientation
.orientation.lock('portrait')
// unlock the orientation
.orientation.unlock()
// current orientation
.orientation
cordova plugin add cordova-plugin-screen-orientation
The orientation is in the primary portrait mode.
The orientation is in the secondary portrait mode.
The orientation is in the primary landscape mode.
The orientation is in the secondary landscape mode.
The orientation is either portrait-primary or portrait-secondary (sensor).
The orientation is either landscape-primary or landscape-secondary (sensor).
orientation is unlocked - all orientations are supported.
// set to either landscape
screen.orientation.lock('landscape');
// allow user rotate
screen.orientation.unlock();
// access current orientation
console.log('Orientation is ' + screen.orientation.type);
Both android and iOS will fire the orientationchange event on the window object. For this version of the plugin use the window object if you require notification.
window.addEventListener("orientationchange", function(){
console.log(screen.orientation.type); // e.g. portrait
});
The 'change' event listener has also been added to the screen.orientation object.
screen.orientation.addEventListener('change', function(){
console.log(screen.orientation.type); // e.g. portrait
});
// OR
screen.orientation.onchange = function(){console.log(screen.orientation.type);
};
The screen.orientation property will not update when the phone is rotated 180 degrees.
Windows store apps (windows-uwp) will only display orientation changes if the device has some sort of accelerometer. The internal state of the "orientation" will still be kept, but the actual screen won't rotate unless the device supports it.