javascriptsafarimobile-safaridevice-orientationdevicemotion

How do I get DeviceOrientationEvent and DeviceMotionEvent to work on Safari?


I'm trying to implement DeviceOrientationEvent and DeviceMotionEvent on my website for a 3D effect. However, the console doesn't log any info and apparently iOS 13 requires a user set permission to start doing this. I can't seem to figure out how to set it up properly.

I've done some research and this is what I found: https://github.com/w3c/deviceorientation/issues/57#issuecomment-498417027

All other methods provided online are not usable anymore sadly.

window.addEventListener('deviceorientation', function(event) {
    console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});

I get the following error message:

[Warning] No device motion or orientation events will be fired until permission has been requested and granted.


Solution

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