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

问题描述 投票:2回答:2

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

ios browser safari ios11 incognito-mode
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');

0
投票

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

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

你可以阅读更多关于它here

© www.soinside.com 2019 - 2024. All rights reserved.