41 lines
1.5 KiB
JavaScript
41 lines
1.5 KiB
JavaScript
(function (global) {
|
|
'use strict';
|
|
function getMiniTool() {
|
|
return global.xhs && global.xhs.miniTool ? global.xhs.miniTool : null;
|
|
}
|
|
function setLocalData(key, data) {
|
|
var serialized = JSON.stringify(data);
|
|
var mt = getMiniTool();
|
|
if (mt && typeof mt.setStorage === 'function') {
|
|
return Promise.resolve(mt.setStorage({ key: key, data: serialized }))
|
|
.then(function () { return true; })
|
|
.catch(function () {
|
|
try { localStorage.setItem(key, serialized); return true; } catch (e) { return false; }
|
|
});
|
|
}
|
|
try { localStorage.setItem(key, serialized); return Promise.resolve(true); } catch (e) {
|
|
return Promise.resolve(false);
|
|
}
|
|
}
|
|
function getLocalData(key) {
|
|
var mt = getMiniTool();
|
|
if (mt && typeof mt.getStorage === 'function') {
|
|
return Promise.resolve(mt.getStorage({ key: key }))
|
|
.then(function (res) {
|
|
var raw = res && (res.data || res);
|
|
if (typeof raw === 'string') {
|
|
try { return JSON.parse(raw); } catch (e) { return null; }
|
|
}
|
|
return raw || null;
|
|
})
|
|
.catch(function () {
|
|
try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch (e) { return null; }
|
|
});
|
|
}
|
|
try { return Promise.resolve(JSON.parse(localStorage.getItem(key) || 'null')); } catch (e) {
|
|
return Promise.resolve(null);
|
|
}
|
|
}
|
|
global.NomadroXhs = { setLocalData: setLocalData, getLocalData: getLocalData };
|
|
})(window);
|