The function DeviceMotionEvent.requestPermission() is unavailable on Chrome and Safari Desktop browsers

Apple made changes in iOS 12.2 by default removing motion sensors from mobile Safari, which was also done recently by Chrome. However, in iOS 13, a requestPermission popup was added back.

.then(response => {
  if (response == 'granted') {
    window.addEventListener('devicemotion', (e) => {
      // do something with e
    })
  }
})
.catch(console.error)

This solution is effective for mobile browsers and they are now functioning properly.

I am encountering issues on non-mobile browsers such as Edge Chromium and Chrome.

Uncaught TypeError: window.DeviceMotionEvent.requestPermission is not a function at game.start_handling (game.js:706)

I believe I need to check if the method or function exists before calling it. Any recommendations?

Answer №1

Confirm availability of requestPermission

It is advisable to first confirm the presence of requestPermission before proceeding.

function establishMotionListeners() {

    if (typeof DeviceMotionEvent.requestPermission === 'function') {

        // Note: You can also utilize "DeviceOrientationEvent" here

        await DeviceMotionEvent.requestPermission()
        .catch( (error) => {
            console.log("Error obtaining sensor permission: %O", error)
            return // Exit out of logic
        })
    }
    
    // ----------------------------------

    // At this juncture...

    // 1 - Browsers that support requestPermission (e.g. Safari iOS)
    // arrive at this stage since users have granted the above permission.

    // 2 - Browsers without requestPermission support (e.g. other browsers)
    // proceed normally, as they bypass the previous 
    // condition check. These browsers automatically prompt the user
    // for permission when the listener is triggered for the first time.

    // 3 - Browsers lacking sensors altogether
    // (e.g. standard desktop devices) disregard all of this, 
    // including your subsequent listeners below.

    // ----------------------------------

    // Define your motion and orientation listeners...

}

Answer №2

I currently check if the browser is mobile to handle a certain situation. While this method works, I believe there may be a more efficient approach.

var check = false;
(function(a){
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d...
  return check;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a problem with the map() function in React.js?

Every time I try to add a new To Do without modifying the HTML at all and push() the array, everything works smoothly. However, once I trigger the onChange event listener, I encounter the error "this.state.tasks.map is not a function". I'm struggling ...

Getting an error message of 'Unable to locate Firebase Storage Default Bucket on the server?

I'm currently facing an issue with the server not being able to locate the bucket. To troubleshoot, I've stored the token and other crucial details in a separate file as a string. Afterwards, I split it and utilize the relevant text in my Javascr ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

What is preventing $scope.$watch from functioning in AngularJS?

I'm struggling to get a $watch function to monitor changes in $scope.data. Here's the code I've been working with: [http://jsbin.com/biqesojaqu/1/edit?html,js,console,output][1] app.html <!DOCTYPE html> <html> <head> < ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Loading data onto a page using jQuery in ASP.NET after a postback

Currently experimenting with a jQuery plugin called jQuery Autocomplete Tokenizer. I'm facing an issue where I need to reload the values back into the textbox after the page is posted back, retaining whatever items were previously entered. Here' ...

Assistance required in designing a unique shape using Three.js

https://i.sstatic.net/pmHP2.png Hello there! I could use some assistance with replicating the 2D shape shown in the image above using three.js. Specifically, I'm encountering some difficulty with incorporating the subtle curvature seen on the inner l ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

Beware: Inaccessible code detected in Reactjs usage

Currently, I am working on a ReactJS project where I have integrated two components - PrescriptionIndex and PrescriptionNew. Let's start with the 'PrescriptionNew' component: import React, { Component } from 'react'; import Flo ...

Locating the point of intersection within a polygon with itself

I am attempting to identify instances of self-intersection in a polygon in order to prevent users from creating them. Users are only permitted to draw the polygon on a plane formed by connecting the coplanar points they plot in 3D space. My initial approa ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

Utilizing Twitter Bootstrap to populate form fields from a dropdown selection

I am currently using twitter bootstrap for my front end web development project. I have successfully implemented a text field with a dropdown menu right next to it: <div class="input-group"> <input type="text" class="form-control" name="ope ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...

The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this: Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"} My goal is to remove any keys within the object that have empty values (""). I attempted the following code snippet: ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

JS templating language inspired by Jinja

I find the django/jinja2 templating languages to be truly exceptional. Their syntax is straightforward yet incredibly flexible. I'm wondering if there is a JavaScript library that offers similar simplicity and versatility, or at least matches their ca ...

Choosing a default selection in a nested v-for loop for a select box

Currently, I have a list of items that users can add new items to. Each item is required to have a select box, and the selected value from the select box should be assigned as the item's value. In an attempt to bind the select box to the item using t ...

Combining multiple responses and storing them all in an array in React JS

I'm currently facing a challenge with async issues while working on an API call that returns IDs. I need to use these IDs to make another call and then combine the responses, but I'm running into problems. const SearchUser = async () => { ...