const TabCounter = require('./TabCounter');
/**
Keeps track of how many tabs a user has open at one time using LocalStorage to store count
@extends TabCounter
@memberof module:Viki
**/
class LocalStorageTabCounter extends TabCounter {
/**
@constructor
@param {String} lsKey - Key for localStorage entry. Defaults to `tabCounter`
**/
constructor(lsKey) {
super({
LS_KEY: lsKey || 'tabCounter',
});
}
/**
@returns {boolean} - Status for localStorage usage. This is inspired by lscache https://github.com/pamelafox/lscache/blob/master/lscache.js#L54
**/
isLocalStorageEnabled() {
if (this.localStorageEnabled !== undefined) {
return this.localStorageEnabled;
}
const key = 'viki-web-utils-random-storage-key';
try {
localStorage.setItem(key, 1);
localStorage.getItem(key);
localStorage.removeItem(key);
this.localStorageEnabled = true;
}
catch(e) {
this.localStorageEnabled = false;
}
return this.localStorageEnabled;
}
/**
@returns {number|null} - Number of tabs open in session or null if localStorage is not working in current browser
**/
getCount() {
if(this.isLocalStorageEnabled()) {
return parseInt(localStorage.getItem(this.options.LS_KEY), 10) || 0;
}
else {
return null;
}
}
saveCount(count) {
this.count = count;
if (this.isLocalStorageEnabled()){
// Fix for safari issue - sometimes throws QUOTA_EXCEEDED_ERR on setItem.
localStorage.removeItem(this.options.LS_KEY);
localStorage.setItem(this.options.LS_KEY, count);
}
}
}
LocalStorageTabCounter.LS_KEY = 'tabCounter';
module.exports = LocalStorageTabCounter;