如何检测iOS 11+ Safari以及旧版Safari中的隐私浏览?

时间:2018-01-09 13:58:22

标签: ios browser safari ios11 incognito-mode

我需要检测用户是否在旧版本以及IOS 11上的Safari中处于私有模式。是否有测试可以覆盖两者?

更新:这是一支笔,试图根据下面的jeprubio解决方案组合存储和openDatabase try-catch块

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+中,非私密模式也被检测为私有模式。

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分:0)

localStorage无法在macOS和iOS上进行隐私浏览。

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

您可以阅读更多相关信息here