πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

The Permissions API: Check Before You Ask

Web FoundationsBrowser APIs🟒 Free Lesson

Checking Permissions Before Asking

The fastest way to make a user distrust a website is to ask for camera access before it has explained why it needs the camera. Browsers compound the problem: once a decision is recorded, the prompt never appears again, so a careless early request silently converts a willing user into a blocked one. The Permissions API exists to let the page ask the browser what the current answer is without asking the user anything.

That distinction is the entire design of the API. navigator.permissions.query returns a status object describing whether the permission is granted, denied, or still awaiting a prompt, and it does so without any visible UI. The status object also emits a change event, so the page can react when the user flips the setting from another tab instead of discovering the change on the next failed call.

The boundaries matter as much as the capabilities:

  • query never prompts; it only reports the recorded state
  • the API does not itself request anything, because each feature owns its request
  • reading a status you have never requested usually reports prompt, which is honest rather than optimistic
  • several permission names are unsupported in some engines and throw instead of resolving
  • a granted status can be revoked at any time, so re-check before critical operations

The Three States and What Produces Them

Each state maps to a concrete user action, and knowing the mapping tells you what your interface should do next.

StateUser has donePrompt appears on request?Your next move
grantedPreviously approved for this originNo, the call succeeds immediatelyProceed, but handle later revocation
deniedPreviously refused, or blocked by policyNo, the call rejects immediatelyShow an explanation and a route to settings
promptNothing yetYes, on a real user gestureAsk at the moment the value becomes useful

Two behaviours surprise newcomers. First, dismissing the prompt without choosing usually records denied, so a distracted user cannot be asked again later in the session; the only recovery path is the browser's site settings panel. Second, a denied state persists across reloads and, in some browsers, across sessions, which is why the built-in prompt should be treated as a one-shot opportunity that you spend carefully.

Querying Status Without Triggering a Prompt

Reading every permission you might eventually need, right after load, is the wrong move for a different reason: it tells the browser nothing useful but fills your startup path with awaits. Query at the point where you are about to show the related feature, and subscribe to changes so the UI stays honest.

<output id="status">Checking permissions…</output>

<script>
const output = document.getElementById('status');
const names = ['camera', 'microphone', 'geolocation', 'notifications'];

function render(name, state) {
  const line = document.createElement('div');
  line.className = `state-${state}`;
  line.textContent = `${name}: ${state}`;
  output.appendChild(line);
}

async function inspect(name) {
  if (!('permissions' in navigator)) {
    output.textContent = 'Permissions API unavailable in this browser.';
    return;
  }

  try {
    const status = await navigator.permissions.query({ name });
    render(name, status.state);
    status.addEventListener('change', () => render(name, status.state));
  } catch (error) {
    // Safari throws for several names; the feature API still works.
    render(name, 'unsupported');
  }
}

for (const name of names) {
  inspect(name);
}
</script>

The try/catch is not defensive padding. Safari rejects query for names it does not map, most notably camera and microphone in some versions, even though getUserMedia works perfectly. Treat query as an enhancement that improves your interface, never as the gate that decides whether the feature exists.

πŸ“Names differ from feature names

Query for geolocation, not location; for clipboard-read, not clipboard. Each name comes from the Permissions Registry, and an unknown name produces a TypeError rather than a promise rejection.

Requesting Only When the User Asks For It

There is no universal permissions.request in the specification, and that is deliberate. Each feature API carries its own request function: getUserMedia for camera and microphone, Notification.requestPermission for notifications, navigator.geolocation.getCurrentPosition for location. The Permissions API reports on the result of those calls rather than replacing them.

The rule that follows is simple: call the request function from inside a click or tap handler. Browsers ignore requests that arrive without a user gesture, and a request fired during page load is either dropped or treated as an automatic denial.

<button id="start">Start video call</button>
<button id="notify">Enable reminders</button>
<p id="feedback" role="status"></p>

<script>
const feedback = document.getElementById('feedback');
let stream = null;

async function requestCamera() {
  try {
    stream = await navigator.mediaDevices.getUserMedia({
      video: { width: { ideal: 1280 }, facingMode: 'user' },
      audio: false
    });
    const video = document.createElement('video');
    video.autoplay = true;
    video.muted = true;
    video.srcObject = stream;
    document.getElementById('preview').replaceChildren(video);
    feedback.textContent = 'Camera is on.';
  } catch (error) {
    const reason = error.name === 'NotAllowedError'
      ? 'Camera access was refused. Allow it in the address bar, then try again.'
      : 'No camera is available on this device.';
    feedback.textContent = reason;
  }
}

async function requestNotifications() {
  if (!('Notification' in window)) {
    feedback.textContent = 'This browser does not support notifications.';
    return;
  }
  const result = await Notification.requestPermission();
  feedback.textContent = result === 'granted'
    ? 'Reminders are enabled.'
    : 'Reminders stay off until you allow notifications in site settings.';
}

document.getElementById('start').addEventListener('click', requestCamera);
document.getElementById('notify').addEventListener('click', requestNotifications);

window.addEventListener('pagehide', () => {
  stream?.getTracks().forEach((track) => track.stop());
});
</script>

Stopping the tracks on page hide is part of the same contract. A camera light that stays on after the user closes the tab is a trust problem, and the browser will eventually kill the stream anyway without telling the page that it did.

Handling Denial Without Nagging

An error name tells you what kind of failure occurred, and each one deserves a different response. NotAllowedError covers both an explicit refusal and a request made outside a user gesture, so the message should offer recovery rather than accuse. NotFoundError means the hardware is absent, which is a permanent condition for this session. NotReadableError usually means another application holds the device. SecurityError means the page is not in a secure context, which is a deployment problem rather than a user problem.

The recovery path is always the same shape: explain in one sentence what the capability enables, provide a button that retries, and link to the browser's site settings panel. Never re-trigger the prompt on every visit. A user who declined twice has told you something; repeating the question is how applications end up on review sites complaining about permission spam.

For flows where the permission is genuinely optional, design the feature to degrade. Video calls can fall back to audio, audio to chat, and chat to a message that says the session is read-only. The permission prompt then becomes an enhancement step rather than a wall at the entrance.

Timing: When the Prompt Earns Its Place

Permission prompts convert better when the user has already seen the payoff. The sequence that works is: show the feature working in a limited form, explain in one sentence what access unlocks, then ask. A video call page that shows a pre-call lobby with a join button has given the user a reason to grant the camera; a landing page that asks on arrival has given them only a mystery.

Consider the difference between two placements of the same prompt. Asking when the user clicks "Start video call" produces a decision made with full context, and a refusal still leaves them able to read the transcript. Asking when the page loads produces a decision made with no context, and a refusal usually costs them the entire experience. The first placement also satisfies the user-gesture requirement for free, because a click is exactly what the browser wants to see.

The copy around the prompt matters as much as its timing. State the benefit in the second person, keep it under ten words, and put any fallback next to the primary action. If the product can continue without the permission, say so before the prompt appears rather than after the refusal, so the choice feels like a preference instead of a toll gate.

πŸ’‘Measure the refusal rate

Log the outcome of each request along with the screen it was fired from. A spike on one screen almost always means the prompt arrived earlier than the explanation did.

Feature Detection and Support

Three layers of detection are needed before you rely on any of this. Confirm the page runs in a secure context, since camera, microphone, and geolocation are unavailable on insecure origins even over localhost in some configurations. Confirm the API exists on the object you intend to call. Confirm the specific permission name is supported by querying it inside a try block.

javascript
function capabilityReport() {
  const secure = window.isSecureContext;
  const canQuery = 'permissions' in navigator;
  const canMedia = Boolean(navigator.mediaDevices?.getUserMedia);
  const canNotify = 'Notification' in window;
  const canGeo = 'geolocation' in navigator;

  const denied = typeof Notification !== 'undefined'
    && Notification.permission === 'denied';

  return { secure, canQuery, canMedia, canNotify, canGeo, denied };
}

const report = capabilityReport();
if (!report.secure) {
  document.getElementById('feedback').textContent =
    'Camera and location require HTTPS.';
}

Report the results to your analytics rather than only to the console. Watching the ratio of granted to denied across releases tells you whether a new prompt is being asked at the right moment, which is the only way to know whether the design is working.

Common Mistakes

Firing getUserMedia during page load so the prompt appears immediately

Fix: Call the request from inside a click handler; browsers ignore gesture-free requests and record a denial.

Treating a failed permissions.query as evidence the feature is missing

Fix: Catch the error and fall back to calling the feature API directly, since several names are unsupported even where the feature works.

Re-prompting on every page visit after a denial

Fix: Show an explanation with a retry button and a link to site settings; the browser will not show its own prompt again.

Leaving the camera stream running after the flow ends

Fix: Stop every track on pagehide or when the preview unmounts so the hardware indicator turns off.

Key Takeaways

  • permissions.query reports state without ever prompting, and its change event keeps the interface honest after settings are altered elsewhere.
  • There is no universal request function; each feature owns its own, and it must run inside a user gesture.
  • Dismissals usually record denial, so spend the built-in prompt only when the value is immediately visible.
  • Unsupported permission names throw rather than reject, which makes try/catch part of the standard flow.
  • Design every gated feature with a working degraded path so refusal costs the user a feature, not the whole page.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement