我需要检测用户是否在旧版本的 Safari 和 IOS 11 上的 Safari 中处于私有模式。是否有涵盖两者的测试?
更新:这是一个尝试结合存储和openDatabase try-catch 块基于jeprubio 的解决方案如下
var isPrivate = false;
// Check private in iOS < 11
var storage = window.sessionStorage;
try {
console.log('first try for storage')
storage.setItem("someKeyHere", "test");
storage.removeItem("someKeyHere");
} catch (e) {
console.log('first catch')
if (e.code === DOMException.QUOTA_EXCEEDED_ERR && storage.length === 0) {
isPrivate = true;
}
}
// Check private in iOS 11: https://gist.github.com/cou929/7973956#gistcomment-2272103
try {
console.log('second try for opendb');
window.openDatabase(null, null, null, null);
} catch (e) {
console.log('second catch');
isPrivate = true;
}
console.log('isPrivate: ' + isPrivate)
alert((isPrivate ? 'You are' : 'You are not') + ' in private browsing mode');
https://codepen.io/anon/pen/zpMZjp
在 Safari 新版本(11+)普通浏览器模式下,控制台上的 openDatabase 测试不会出错,但会进入第二个 catch 并且 isPrivate 设置为 true。因此,在 Safari 11+ 中,非隐私模式也被检测为隐私模式。