The error "navigator.permissions.query is not a defined object" is encountered in the evaluation

Whenever I try to access my website on an iPhone 7, I encounter a frustrating error. The main screen loads without any issues, but as soon as I click on something, a white bank screen appears.

I believe this piece of code might be the cause:

  useEffect(() => {
    navigator.permissions
      .query({ name: "microphone" })
      .then((permissionStatus) => {
        setMicrophonePermissionGranted(permissionStatus.state === "granted");

        permissionStatus.onchange = function () {
          setMicrophonePermissionGranted(this.state === "granted");
        };
      });

    navigator.permissions.query({ name: "camera" }).then((permissionStatus) => {
      setCameraPermissionGranted(permissionStatus.state === "granted");

      permissionStatus.onchange = function () {
        setCameraPermissionGranted(this.state === "granted");
      };
    });
  }, []);

Is there any way to resolve this issue?

Answer №1

To ensure that you can access location data, it's important to check if permission APIs are available. If they are not available, you can then query the standard APIs as an alternative.

Take a look at this example demonstrating how to obtain location information: Permissions API Navigation API

if ( navigator.permissions && navigator.permissions.query) {
//prioritize permissions APIs
  navigator.permissions.query({ name: 'geolocation' }).then(function(result) {
      // Possible outcomes include 'granted', 'prompt', and 'denied'
      const permission = result.state;
      if ( permission === 'granted' || permission === 'prompt' ) {
          _onGetCurrentLocation();
      }
  });
} else if (navigator.geolocation) {
//fallback to Navigation APIs
  _onGetCurrentLocation();
}

function _onGetCurrentLocation () {
    navigator.geolocation.getCurrentPosition(function(position) {
        //simulate constructing map latitude and longitude
        const marker = { 
          lat: position.coords.latitude, 
          lng: position.coords.longitude 
        };
    })
}

Answer №2

Permissions.query() is regarded as an experimental feature since June 2021 https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query.

Currently, this translates into the need for two different user interfaces and workflows: one that can support elaborate flows to guide users on how to proceed, and another more conventional approach using try / catch blocks. Here's an example:

useEffect(() => {
    requestPermissions();
}, []);

const requestPermissions = async () => {
    try {
        handlePermissionsGranted();
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        startRecording();
    } catch {
        ...
    }
};

const handlePermissionsGranted = async () => {
    if (navigator.permissions && navigator.permissions.query) {
        const permissions = await navigator.permissions.query({name: 'microphone'});
        permissions.onchange = () => {
          setMicrophonePermissionGranted(permissions === 'granted');
        };
    } 
};

const startRecording = async () => {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
        const mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm' });
        ...
    } catch {
        ... << if you reach this catch means that either the browser does not support webrtc or that the user didn't grant permissions
    }
};

Answer №3

My aim was to verify the availability of microphone and camera permissions on iOS devices as well as on the Facebook browser. However, I discovered that these features are not supported in those environments, causing the entire process to fail. To resolve this issue, I relocated the query to a component that is only loaded when accessed through non-mobile devices.

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

Looking for a Webpack setup for a React Components Library that includes Typescript, SASS, CSS Modules, and SASS support

I'm on the lookout for a functional Webpack configuration tailored for a React Components Library that includes TypeScript, SASS, and CSS Modules with SASS support. If anyone has one they'd like to share, I would be extremely grateful! ...

TextField from MUI isn't updating with react-hook-form, onChange event is not triggering

const [userInfo, setUserInfo] = useState({ fullName: "", email: "", }); // State for user information const handleChange = (event) => { console.log(event.target.value); }; // Function to handle input changes <Grid contain ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library. My website features several cards, and my goal is to showcase a spinner during the image loadin ...

Steps to make pop-up iframe function on the same page within a react nextjs application

My vanilla Html app has a pop-up feature that functions perfectly. When the button is clicked, the pop-up opens and everything works as expected. However, I am encountering an issue when trying to implement this same functionality in my React, NextJS app. ...

Reset the input field upon button press

Is there a way to clear the input field after pressing the button? <div class="form-group autocomplete"> <div class="input-group search"> <input id="search" name="searchterm" type="search" class="form-control form-control search-input" pl ...

Do you have any suggestions on how to fix this npm SQLite installation issue?

Could use some help with an SQLite installation error I'm encountering. Any ideas on what the issue might be and how to resolve it? C:\Users\jacka\Downloads\discord-emoji-stealer-master\discord-emoji-stealer-master>npm i & ...

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

Yarn combined with Webpack fails to execute post-compilation tasks

When using yarn and running yarn prod, I encountered the following error: https://i.stack.imgur.com/2emFk.jpg It seems to be stuck at this particular part of the code: mix.then(() => { execSync(`npm run rtlcss ${__dirname}/Assets/css/admin.css ${__dir ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

Error with SWR hook: "Fetcher argument not supplied"

Using the SWR hook for the first time, everything is working smoothly so far. However, I've encountered an error that I can't seem to figure out. Let me share my code with you. This is the global configuration: <AuthContext> {isValidRo ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

Achieving function components within React Router Dom V6

I need help with keeping my sidebar as a continuous function component without re-rendering every time the page changes from "/dashboard" to "/chat". This is how it looks currently: <div className="flex flex-col "> <BrowserRouter> ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

The React app was successfully deployed to localhost:3000, but when attempting to access it, the message "This site can't be reached" is displayed. Strangely, the terminal confirms that the app is indeed

I've checked my code thoroughly, but when I deploy it to localhost, something seems off. Even after disabling all the components and running npm install, the issue persists. https://i.stack.imgur.com/i04eY.png Oddly enough, everything seems fine in ...

Is Mobile Safari causing issues with React PWA when uploading images?

We were surprised by the lack of information online regarding this issue, so we are reaching out here in hopes of finding a solution. When using an iPhone with mobile safari, we encountered a problem while running two simple tests. One test works fine, wh ...