How do I get DeviceOrientationEvent and DeviceMotionEvent to work on Safari?
As of iOS 13 beta 2, you need to call DeviceOrientationEvent.requestPermission() to access to gyroscope or accelerometer. This will present a permission dialog prompting the user to allow motion and orientation access for this site.
Note that this will not work if you try to call it automatically when the page loads. The user needs to take some action (like tapping a button) to be able to display the dialog.
Also, the current implementation seems to require that the site have https enabled.
For more information, see this page
if ( location.protocol != "https:" ) {
location.href = "https:" + window.location.href.substring( window.location.protocol.length );
}
function permission () {
if ( typeof( DeviceMotionEvent ) !== "undefined" && typeof( DeviceMotionEvent.requestPermission ) === "function" ) {
// (optional) Do something before API request prompt.
DeviceMotionEvent.requestPermission()
.then( response => {
// (optional) Do something after API prompt dismissed.
if ( response == "granted" ) {
window.addEventListener( "devicemotion", (e) => {
// do something for 'e' here.
})
}
})
.catch( console.error )
} else {
alert( "DeviceMotionEvent is not defined" );
}
}
const btn = document.getElementById( "request" );
btn.addEventListener( "click", permission );
Use an element on your page to use as the event trigger and give it an id of "request".
This will check for https and change it if required before requesting API authorization. Found this yesterday but do not remember the URL.
You need a click or a user gesture to call the requestPermission(). Like this :
<script type="text/javascript">
function requestOrientationPermission(){
DeviceOrientationEvent.requestPermission()
.then(response => {
if (response == 'granted') {
window.addEventListener('deviceorientation', (e) => {
// do something with e
})
}
})
.catch(console.error)
}
</script>
<button onclick='requestOrientationPermission();'>Request orientation permission</button>
Note : if you click on cancel on the permission prompt and want to test it again, you will need to quit Safari and launch it back for the prompt to come back.