Detecting Safari Private Browsing Mode

Detecting Safari Private Browsing Mode

2月 6, 2018 · 1 分钟阅读时长 · 107 字 · -阅读 -评论

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.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源