Last active
January 7, 2021 12:16
-
-
Save marcofugaro/922bceb1d2ac44bd3934f16be124821e to your computer and use it in GitHub Desktop.
Function to request device orientation on Android and iOS devices, remember to use HTTPS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function requestDeviceOrientation(fn, createTrigger) { | |
// iOS 13+ | |
if ( | |
window.DeviceOrientationEvent !== undefined && | |
typeof window.DeviceOrientationEvent.requestPermission === 'function' | |
) { | |
// check if the user gave permissin in the past | |
window.DeviceOrientationEvent.requestPermission().then((response) => { | |
if (response == 'granted') { | |
fn() | |
} | |
}).catch(() => { | |
// otherwise create a trigger and requestPermission on click | |
let trigger | |
switch(typeof createTrigger) { | |
case 'function': | |
trigger = createTrigger() | |
break | |
case 'object': | |
trigger = createTrigger | |
break | |
default: | |
throw new Error(`Trigger function or element not provided`) | |
} | |
document.body.appendChild(trigger) | |
trigger.addEventListener('click', () => { | |
window.DeviceOrientationEvent.requestPermission().then((response) => { | |
if (response === 'granted') { | |
fn() | |
document.body.removeChild(trigger) | |
} | |
}) | |
}) | |
}) | |
} else { | |
// normal android behaviour | |
fn() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment