如何应对用户使用无痕浏览模式

在开发过程中,由于一些页面会使用localStorage,sessionStorage ,在无痕浏览模式,本地存储不能用,会出现很多问题,看到过一种解决方案

function isStorageSupported() {
    let testKey = 'test',
        storage = window.localStorage
    try {
        storage.setItem(testKey, 'testValue')
        storage.removeItem(testKey)
        /*
         因为重写覆盖localStorage的setItem的方法后,再次执行这个函数一定会返回true,
         那么如何在任何知道是否在隐身模式下呢?一个简单的方法是在window下添加一个属性标记。
         这个方法的坏处就是需要多维护一个变量。
         还有一个办法是为isStorageSupported方法添加memoize控制。关于Memoize可以看我上一篇文章
        */

        window.isStorageSupportedFlag = true
        return true
    } catch (error) {
        window.isStorageSupportedFlag = false
        layer.open({content: '隐私/无痕模式效果会不太好哦!请切换到正常模式'})
        return false
    }
}

//解决方案二

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.

if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

如果实在Angular 里面可以使用$cacheFactory 在其他需要的地方使用依赖注入的方法,保存一个全局变量,对于一些其他的常用框架又是怎么处理的呢?

app.factory('Cache', ['$cacheFactory', function($cacheFactory) {
    return $cacheFactory('cache');
}]);
阅读 9.7k
3 个回答

其他哪些框架啊,23333。

vue的话,直接在根组件上挂一个全局变量,子组件引用,同步更新就行了。

react的话同理。

reduce等方案,直接在store里挂一个全局变量。

并不认为用户在使用无痕浏览模式的时候期望网站会记录下自己的浏览痕迹

就四个字~

后台支撑~

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题