Detecting Safari Private Browsing Mode

· 1 min read · 107 Words · -Views -Comments

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