Detecting Safari Private Browsing Mode
2月 6, 2018
·
1 分钟阅读时长
·
107
字
·
-阅读
-评论
Cookies gave us personalization; HTML5 added
localStorageandsessionStorage. 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
- Apple support article on private browsing: https://support.apple.com/HT203036
Notes
I avoid touching localStorage or sessionStorage directly for detection because Safari 11 changed how those APIs behave. Probing openDatabase still works reliably.

