2

我需要检测用户是否在旧版本的 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+ 中,非隐私模式也被检测为隐私模式。

4

2 回答 2

2

尝试这个:

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');
于 2018-01-13T00:41:24.893 回答
1

localStorage不适用于 macOS 和 iOS 上的隐私浏览。

如果你尝试setItem,它会抛出一个错误。这应该允许您检测隐私浏览。

你可以在这里阅读更多关于它的信息

于 2018-01-09T14:20:22.560 回答