Spaces:
Sleeping

Login / app.py
Pezh's picture
Create app.py
00483cb verified
Raw History Blame Contribute Delete
1.73 kB
import streamlit as st
from datetime import datetime, timedelta
# Custom function to display HTML content with Streamlit's components.v1.html()
def local_storage_button():
button_html = f"""
<button onclick="incrementCounter()">Click it</button>
<p id='counter'></p>
<script>
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
if (now.getTime() > item.expiry) {
localStorage.removeItem(key)
return null
}
return item.value
}
function incrementCounter() {{
let count = getWithExpiry('click_count') 0;
let expiry = getWithExpiry('expiry_time') new Date().getTime() + (24 * 60 * 60 * 1000);
if (count < 10 && new Date().getTime() < expiry) {{
count++;
localStorage.setItem('click_count', JSON.stringify({{value: count, expiry}}));
localStorage.setItem('expiry_time', JSON.stringify({{value: expiry, expiry}}));
window.location.reload(); // Reload the page to refresh the count display
}}
}}
// Set initial count on page load/reload
window.onload = (event) => {{
let count = getWithExpiry('click_count') 0;
document.getElementById('counter').innerText = `Button has been clicked ${count} times.`;
}};
</script>
"""
st.components.v1.html(button_html, height=100)
# Use the custom function to display the button
local_storage_button()