Nick Wilkins
Nick Wilkins

Reputation: 301

Storing DeviceOrientationEvent and DeviceMotionEvent permissions across pages

I've got a nice DeviceMotionEvent request all working for Safari (or other browsers that require the permission), something along these lines:

// on click of a button
DeviceMotionEvent.requestPermission()
.then(response => {
    if (response == 'granted') {
        // do my thing
    }
})
.catch(function(error) {
    console.log(error);
    // do my other thing
});

And thats working great. But when a user goes to a new page, they have to request the permission again. Obviously I'm calling 'requestPermission' again, so of course they would do.

How do I find out if permission has already been granted? Or is permission granted on a page by page basis (rather than session / site basis)?

I could store the response in localstorage or something, but would prefer something along the lines of:

DeviceMotionEvent.permissionStatus

Or something?

Upvotes: 2

Views: 402

Answers (3)

bumsoverboard
bumsoverboard

Reputation: 891

You should be able to check whether permissions have been granted using the devicemotion eventListener. Baring in mind you have to push a button or similar to run DeviceMotionEvent.requestPermission()

eg.

let hasOrientationControls = false;
window.addEventListener("devicemotion", () => {
    hasOrientationControls = true;
});


// then when the button is pressed we can request permissions if we need
onButtonPressed () => {
   if (hasOrientationControls) return;
   else DeviceMotionEvent.requestPermission();
}

I've also used this

isVRReady = window.DeviceOrientationEvent && "ontouchstart" in window;

Upvotes: 0

rags2riches-prog
rags2riches-prog

Reputation: 1761

Edited: You can use the Web Storage API with the following two mechanisms:

  • sessionStorage
  • localStorage

As the names imply, these two interfaces are ideal for session-based data or if you want to persist state even after the connection is closed.

Upvotes: -1

David Bradshaw
David Bradshaw

Reputation: 13077

I think you only option is to build a single page application and use the history.pushState() to update the location in the browser, when you wish to ‘change pages’.

Upvotes: 1

Related Questions