最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - localStorage.removeItem not working properly . How can i fix it? - Stack Overflow

programmeradmin1浏览0评论

I have this code for saving data from 2 inputs. Everything is all right when the page refreshes twice (the data is saved) but on third one the date disappear. I know this is because of the localStorage.removeItem, but I need the data to disappear after the tab is gone.

I use the same method for other stuff and it's working perfect. but in this case it's how I said , working for just 2 refreshes .

<input type="date" id="exdated" name="" 
        onfocus="localStorage.setItem('myTestApp','exdated')" 
        onkeyup="saveValue(this);">
<br><br> 
<input type="date" id="datata" name="" 
        onfocus="localStorage.setItem('myTestApp','datata')" 
        onkeyup="saveValue(this);">
<br><br>
let today = new Date().toISOString().slice(0, 10)

document.getElementById("datata").value = getSavedValue("datata"); 
document.getElementById("exdated").value = getSavedValue("exdated"); 

function saveValue(e) {
    var id = e.id;  
    var val = e.value; 
 
    localStorage.setItem(id, val); 
}

function getSavedValue  (v) {
    if (!localStorage.getItem(v)) {
      return today;
    }

    var itemcheta = localStorage.getItem(v);
    localStorage.removeItem(v); 
    
    return itemcheta;
}

I have this code for saving data from 2 inputs. Everything is all right when the page refreshes twice (the data is saved) but on third one the date disappear. I know this is because of the localStorage.removeItem, but I need the data to disappear after the tab is gone.

I use the same method for other stuff and it's working perfect. but in this case it's how I said , working for just 2 refreshes .

<input type="date" id="exdated" name="" 
        onfocus="localStorage.setItem('myTestApp','exdated')" 
        onkeyup="saveValue(this);">
<br><br> 
<input type="date" id="datata" name="" 
        onfocus="localStorage.setItem('myTestApp','datata')" 
        onkeyup="saveValue(this);">
<br><br>
let today = new Date().toISOString().slice(0, 10)

document.getElementById("datata").value = getSavedValue("datata"); 
document.getElementById("exdated").value = getSavedValue("exdated"); 

function saveValue(e) {
    var id = e.id;  
    var val = e.value; 
 
    localStorage.setItem(id, val); 
}

function getSavedValue  (v) {
    if (!localStorage.getItem(v)) {
      return today;
    }

    var itemcheta = localStorage.getItem(v);
    localStorage.removeItem(v); 
    
    return itemcheta;
}
Share edited Sep 9, 2021 at 8:28 Lajos Arpad 77.1k40 gold badges117 silver badges222 bronze badges asked Sep 1, 2021 at 11:29 stoperanstoperan 311 silver badge11 bronze badges 7
  • There is too much whitespace in the declaration of getSavedValue (v) {...} - it should be getSavedValue(v) {...} – biberman Commented Sep 1, 2021 at 11:41
  • you never use saveValue() so your localeStorage is empty and localStorage.removeItem(v) is never called. – Mister Jojo Commented Sep 1, 2021 at 12:02
  • @MisterJojo i use this on my input <input type="date" id="exdated" name="" onfocus="localStorage.setItem('myTestApp','exdated')" onkeyup="saveValue(this);"><br><br> <input type="date" id="datata" name="" onfocus="localStorage.setItem('myTestApp','datata')" onkeyup="saveValue(this);"><br><br> – stoperan Commented Sep 1, 2021 at 12:15
  • Please include a plete minimal reproducible example. – fdomn-m Commented Sep 1, 2021 at 12:16
  • 3 Why don't you use sessionStorage instead of localStorage? This seems to be what you want. You also don't have to remove values then. – maraca Commented Sep 6, 2021 at 13:01
 |  Show 2 more ments

3 Answers 3

Reset to default 6

Since you want the data to disappear when the browser tab closes, you should use sessionStorage instead of localStorage. This will let the browser handle the correct removal of the data when the browsing session closes, so it's less code to worry about.

You have onfocus and onkeyup events that load/save the data and on load these two lines initiate it:

document.getElementById("datata").value = getSavedValue("datata"); 
document.getElementById("exdated").value = getSavedValue("exdated");

Tab or window close can be handled by a beforeunload event

window.addEventListener('beforeunload', function (e) {
    //Do some stuff
});

which you can use in order to handle tab/window close or the load of another page in the tab. However, this will run even if you reload the page in the tab. Another problem is that you might have other tabs opened and pointing to the same page as well.

So, how could one cope with this?

Due to the fact that your Javascript code can be found by any developer opening your page in your browser, encoding the value and decoding via Javascript is not really an option. You could use sessionStorage, like others suggested, but that will not work well in the case when you close your tab, open another tab and load the page again.

In my opinion at the point when the resources are unloaded, you cannot know for sure whether it's a tab closing, a reloading, navigation to another website or window closing. As a result, you need to delegate the logic that determines whether the item is to be removed from the storage to the page load.

So, something like this function may help you at page load:

function handleStorage() {
    let date = new Date(localStorage.getItem('savetime'));
    if ((date.getTime()) && ((new Date() - date) / 60000 > 5)) { //5 minutes
        localStorage.removeItem('datadata');
        localStorage.removeItem('exdated');
    }
}

So, no matter how many tabs you have where this page is opened, if at page load the last save is older than a certain amount of time, 5 minutes (you can decrease this time if it is more convenient that way), for instance, then you clear the saved data. Naturally, at saveValue you will need to save the date as well:

function saveValue(e) {
    var id = e.id;  
    var val = e.value; 
 
    localStorage.setItem(id, val);
    localStorage.setItem('savetime', new Date());
}

and then you can remove the localStorage.removeItem call from getSavedValue, where it's inappropriate anyway, since you may need to get the value multiple times for some reason.

You have to use onchange="saveValue(this);" and not onkeyup="saveValue(this);"

Demo / Note localStorage does not work on Stack Overflow

<input type="date" id="exdated" name="" onfocus="localStorage.setItem('myTestApp','exdated')" onchange="saveValue(this);">
<br><br>
<input type="date" id="datata" name="" onfocus="localStorage.setItem('myTestApp','datata')" onchange="saveValue(this);">
<br><br>
<script>
  let today = new Date().toISOString().slice(0, 10)

  document.getElementById("datata").value = getSavedValue("datata");
  document.getElementById("exdated").value = getSavedValue("exdated");

  function saveValue(e) {
    var id = e.id;
    var val = e.value;

    localStorage.setItem(id, val);
    console.log(localStorage)
  }

  function getSavedValue(v) {
    if (!localStorage.getItem(v)) {
      return today;
    }

    var itemcheta = localStorage.getItem(v);
    localStorage.removeItem(v);

    return itemcheta;
  }

</script>

JS-fiddle demo

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>