简体   繁体   中英

Set the time for html local storage

I have this html local storage, that saves a cookie, but I want that if the browser restarts this cookie dont be available again, so if the user visits the site it will show the popup again

    $(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.
    });

});

I dont know how to set a life time for this, like 10 min or something

localStorage does not have any expiry time. But you can implement your own logic while reading/writing to localStorage .

For example, along with the actual data you can store the expiry time as well and while reading check if the time is past the expiry time then consider the value unavailable.

Example code (from 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
}

Usage -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM