Skip to content

Instantly share code, notes, and snippets.

@marcofugaro
Last active January 7, 2021 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcofugaro/922bceb1d2ac44bd3934f16be124821e to your computer and use it in GitHub Desktop.
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
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