设置 html 本地存储的时间

Set the time for html local storage

我有这个 html 本地存储,它保存了一个 cookie,但我希望如果浏览器重新启动,这个 cookie 将不再可用,所以如果用户访问该网站,它将再次显示弹出窗口

    $(document).ready(function() {
    if(localStorage.getItem('popState') != 'shown'){
        $("#popup").delay(2000).fadeIn();
        localStorage.setItem('popState','shown')
    }

    $('#popup-close').click(function(e) // You are clicking the close button
    {
    $('#popup').fadeOut(); // Now the pop up is hiden.
    });

});

我不知道如何为此设置生命周期,例如 10 分钟或其他

localStorage 没有任何到期时间。但是您可以在 reading/writing 到 localStorage.

时实现自己的逻辑

例如,除了实际数据,您还可以存储到期时间,在读取时检查时间是否超过到期时间,然后考虑该值不可用。

示例代码(来自here)-

function setLocalStorageItemWithExpiry(key, value, expiryTimeInMs) {
    const now = new Date()

    // `item` is an object which contains the original value
    // as well as the time when it's supposed to expire
    const item = {
        value: value,
        expiry: now.getTime() + expiryTimeInMs,
    }
    localStorage.setItem(key, JSON.stringify(item))
}

function getLocalStorageItemWithExpiry(key) {
    const itemStr = localStorage.getItem(key)
    // if the item doesn't exist, return null
    if (!itemStr) {
        return null
    }
    const item = JSON.parse(itemStr)
    const now = new Date()
    // compare the expiry time of the item with the current time
    if (now.getTime() > item.expiry) {
        // If the item is expired, delete the item from storage
        // and return null
        localStorage.removeItem(key)
        return null
    }
    return item.value
}

用法 -

const value = getLocalStorageItemWithExpiry('myKey');
if (!value) {
    // Your logic
    setLocalStorageItemWithExpiry('myKey', 'testvalue', 60000); // 60000 ms = 1 min
}