我需要检测用户在旧版本的 Safari 以及 IOS 11 上的 Safari 中是否处于私密模式。是否有一个测试可以涵盖这两种模式?
更新:这是一支笔,尝试根据下面的 jeprubio 解决方案将存储和 openDatabase try-catch block 结合起来
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 测试中不会出错,但会进入第二个捕获并且 isPrivate 设置为 true。因此,在 Safari 11+ 中,非隐私模式也会被检测为隐私模式。
最佳答案
试试这个:
var isPrivate = false;
// Check private in iOS < 11
var storage = window.sessionStorage;
try {
storage.setItem("someKeyHere", "test");
storage.removeItem("someKeyHere");
} catch (e) {
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 {
window.openDatabase(null, null, null, null);
} catch (_) {
isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t') + ' in private browsing mode');
关于ios - 如何检测 iOS 11+ Safari 以及旧版本 Safari 中的隐私浏览?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169810/