Detecting Safari Private Browsing Mode

Shows how to detect Safari’s private browsing mode so you can warn users about disabled local storage.

Feb 6, 2018 · 1 min read · 107 Words · -Views -Comments · Programming
Frontend 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Cookies gave us personalization; HTML5 added localStorage and sessionStorage. Safari, however, blocks local storage APIs entirely when private browsing is enabled. Calls throw errors, so we may want to detect the mode and inform the user.

Code

function isPrivateMode() {
  let isPrivate = false;
  try {
    window.openDatabase(null, null, null, null);
  } catch (e) {
    isPrivate = true;
  }
  return isPrivate;
}

if (isPrivateMode()) {
  alert('Local storage is unavailable. Please disable private browsing.');
  window.location.href = 'https://support.apple.com/HT203036';
}

Reference

Notes

I avoid touching localStorage or sessionStorage directly for detection because Safari 11 changed how those APIs behave. Probing openDatabase still works reliably.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover