在Polymer中使用会话存储web中的数据
Use data from session storage web in Polymer
我有一个用Polymer制作的网站,当你登录时,它会在会话存储中向你返回一个值为docID、name、姓氏和姓氏2的密钥userData,然后它进入平台。这些值存储在浏览器的会话存储中。
我想使用除docID之外的那些值,并将其带到我的代码中,以便在登录视图/页面中绘制它,但我不知道如何使用会话存储来获取这些参数。
我做了一个假用户,但使用了上次连接时可用的本地存储,但我不知道如何将其用于会话和从网站接收数据。这是我的脚本:
Polymer({
date: null,
timeDate: null,
keyStorage: 'lastConnection',
ready: function(){
this.storageDate();
this.timeDate = this.getLastDateConnection();
this.storageUser();
this.fakeUserName = this.getUser();
},
getLastDateConnection: function(){
var date = new Date(parseInt(localStorage.getItem(this.keyStorage)));
return [date.getHours(),('0'+date.getMinutes()).slice(-2)].join(':');
},
storageDate: function(){
localStorage.setItem(this.keyStorage, +new Date);
},
getUser: function(){
var name = [localStorage.getItem("firstname") + " " + localStorage.getItem("lastname")];
return name;
},
storageUser:function(){
localStorage.setItem("lastname", "Vader");
localStorage.setItem("firstname", "Dark");
}
});
我想做一些类似的事情,除了我必须用会话存储和从网站存储用户数据(在有人登录之前我不知道信息),所以我想我不应该做setItem,只是做了一个getItem,从网站接收密钥"userData"。有什么帮助/想法吗?谢谢
PS:如果我想保留用户名,也许我应该在从会话存储收到userData后将用户信息存储在本地存储中?我想做的事情与谷歌对我们的gmail账户所做的一样(你登录后,当你想再次输入时,它会存储你的账户)。
好吧,我想我明白了。
在就绪函数中,调用存储会话存储的函数:
ready: function(){
this.setData();
this.myUser = this.storageUser();
},
setData: function() {
sessionStorage.setItem("userData",userData);
},
然后将会话存储在本地进行对象解析:
storageUser: function(){
var userData = sessionStorage.getItem("userData");
var myObject = JSON.parse(userData);
var userName = [myObject.name + " " + myObject.surname];
return userName;
},
这是有原则的。
我知道这是一篇旧帖子,但对于登录此页面的新人来说,这个session storage
元素可能会有所帮助。它的行为与local storage
完全相同。
<!--
@license
Copyright (c) 2015 The PlatinumIndustries.pl. All rights reserved.
This code may only be used under the BSD style license.
-->
<link rel="import" href="../polymer/polymer.html">
<!--
Element access to Web Storage API (window.sessionStorage).
Keeps `value` property in sync with sessionStorage.
Value is saved as json by default.
### Usage:
`Ss-sample` will automatically save changes to its value.
<dom-module id="ls-sample">
<iron-sessionstorage name="my-app-storage"
value="{{cartoon}}"
on-iron-sessionstorage-load-empty="initializeDefaultCartoon"
></iron-sessionstorage>
</dom-module>
<script>
Polymer({
is: 'ls-sample',
properties: {
cartoon: {
type: Object
}
},
// initializes default if nothing has been stored
initializeDefaultCartoon: function() {
this.cartoon = {
name: "Mickey",
hasEars: true
}
},
// use path set api to propagate changes to sessionstorage
makeModifications: function() {
this.set('cartoon.name', "Minions");
this.set('cartoon.hasEars', false);
}
});
</script>
### Tech notes:
* * `value.*` is observed, and saved on modifications. You must use
path change notifification methods such as `set()` to modify value
for changes to be observed.
* * Set `auto-save-disabled` to prevent automatic saving.
* * Value is saved as JSON by default.
* * To delete a key, set value to null
* Element listens to StorageAPI `storage` event, and will reload upon receiving it.
* **Warning**: do not bind value to sub-properties until Polymer
[bug 1550](https://github.com/Polymer/polymer/issues/1550)
is resolved. session storage will be blown away.
`<iron-sessionstorage value="{{foo.bar}}"` will cause **data loss**.
@demo demo/index.html
@hero hero.svg
-->
<dom-module id="iron-sessionstorage"></dom-module>
<script>
Polymer({
is: 'iron-sessionstorage',
properties: {
/**
* SessionStorage item key
*/
name: {
type: String,
value: ''
},
/**
* The data associated with this storage.
* If set to null item will be deleted.
* @type {*}
*/
value: {
type: Object,
notify: true
},
/**
* If true: do not convert value to JSON on save/load
*/
useRaw: {
type: Boolean,
value: false
},
/**
* Value will not be saved automatically if true. You'll have to do it manually with `save()`
*/
autoSaveDisabled: {
type: Boolean,
value: false
},
/**
* Last error encountered while saving/loading items
*/
errorMessage: {
type: String,
notify: true
},
/** True if value has been loaded */
_loaded: {
type: Boolean,
value: false
}
},
observers: [
'_debounceReload(name,useRaw)',
'_trySaveValue(autoSaveDisabled)',
'_trySaveValue(value.*)'
],
ready: function() {
this._boundHandleStorage = this._handleStorage.bind(this);
},
attached: function() {
window.addEventListener('storage', this._boundHandleStorage);
},
detached: function() {
window.removeEventListener('storage', this._boundHandleStorage);
},
_handleStorage: function(ev) {
if (ev.key == this.name) {
this._load(true);
}
},
_trySaveValue: function() {
if (this._doNotSave) {
return;
}
if (this._loaded && !this.autoSaveDisabled) {
this.debounce('save', this.save);
}
},
_debounceReload: function() {
this.debounce('reload', this.reload);
},
/**
* Loads the value again. Use if you modify
* sessionStorage using DOM calls, and want to
* keep this element in sync.
*/
reload: function() {
this._loaded = false;
this._load();
},
/**
* loads value from session storage
* @param {boolean=} externalChange true if loading changes from a different window
*/
_load: function(externalChange) {
var v = window.sessionStorage.getItem(this.name);
if (v === null) {
this._loaded = true;
this._doNotSave = true; // guard for save watchers
this.value = null;
this._doNotSave = false;
this.fire('iron-sessionstorage-load-empty', { externalChange: externalChange});
} else {
if (!this.useRaw) {
try { // parse value as JSON
v = JSON.parse(v);
} catch(x) {
this.errorMessage = "Could not parse session storage value";
console.error("could not parse sessionstorage value", v);
v = null;
}
}
this._loaded = true;
this._doNotSave = true;
this.value = v;
this._doNotSave = false;
this.fire('iron-sessionstorage-load', { externalChange: externalChange});
}
},
/**
* Saves the value to localStorage. Call to save if autoSaveDisabled is set.
* If `value` is null or undefined, deletes localStorage.
*/
save: function() {
var v = this.useRaw ? this.value : JSON.stringify(this.value);
try {
if (this.value === null || this.value === undefined) {
window.sessionStorage.removeItem(this.name);
} else {
window.sessionStorage.setItem(this.name, /** @type {string} */ (v));
}
}
catch(ex) {
// Happens in Safari incognito mode,
this.errorMessage = ex.message;
console.error("sessionStorage could not be saved. Safari incoginito mode?", ex);
}
}
/**
* Fired when value loads from localStorage.
*
* @event iron-localstorage-load
* @param {{externalChange:boolean}} detail -
* externalChange: true if change occured in different window.
*/
/**
* Fired when loaded value does not exist.
* Event handler can be used to initialize default value.
*
* @event iron-localstorage-load-empty
* @param {{externalChange:boolean}} detail -
* externalChange: true if change occured in different window.
*/
});
</script>
相关文章:
- Html5 Web 存储未在第二页中显示数据
- 无法使用HTML5 Web存储保存布尔值的解决方法
- 围绕web存储的Javascript API包装器
- jQuery:在输入字段上使用Web存储/本地存储
- HTML5 Web 存储创建变量
- Web存储(sessionStorage和localStorage)处于私人浏览模式(隐姓埋名)
- 从上游处理本地web存储更改的建议方法是什么
- 不能将数组或对象设置为html5 web存储
- 为什么这个web存储代码不能工作?
- HTML5 Web存储-存储JSON数据,然后检索它
- 如何处理Web存储的大小限制?
- 如何将字符串从asp.net代码传递到本地web存储
- 使用HTML5 web存储将用户输入保存在HTML页面上
- 如何在JS中实现Web存储持久化
- Javascript存储一个数字,以便以后与web存储一起使用
- 从 Web 存储加载包含 HTML 的页面
- 我如何使用html, javascript web存储登录脚本
- 如何在javascript中添加/追加到现有的Web存储
- 是否有一种方法来阻止Web存储和IndexedDB关于模式的一部分起源
- 检查Web存储可用性的奇怪行为