Detecting Event when User Refreshes the Websie / Closes Browser Tab

Hello Everyone,

I’m using Streamlit and trying to catch the event when the user refreshes the tab or close it in order to delete some files created.

I checked the JavaScript injection into Streamlit, but apparently it is not working.

Here is my code:

set_local_storage = """
<script>
window.addEventListener('beforeunload', function (e) {
    console.log("page is about to be unloaded. set page refresh to true in set local storage")
    localStorage.setItem('page_refresh', 'true');
});
</script>"""

check_local_storage = """
<script>
console.log("check local storage")
document.addEventListener('DOMContentLoaded', function() {
    const pageRefresh = localStorage.getItem('page_refresh');
    console.log('page refresh status: ', pageRefresh)
    if (pageRefresh === 'true') {
        console.log("pageRefresh is true")
        localStorage.setItem('page_refresh', 'false');
        console.log("localStorage")
        console.log(localStorage)
        document.body.setAttribute('data-page-refresh', 'true');
        console.log("document.body")
        console.log(document.body)
    }
    else
    {
        console.log("document.body in else")
        console.log(document.body)
        document.body.setAttribute('data-page-refresh', 'false');
    }
});
</script>"""

def main():
    st.set_page_config(page_title="Your Assistant")
    st.markdown("""< !DOCTYPE
    html>
    <html>
    <head>
    <title> Test
    JavaScript
    Injection </title>
    </head>
    <body>
    <h1> JavaScript
    Injection
    Test </h1>
    <script>
    console.log("Basic JavaScript is running 0");
    </script>
    </body>
    </html>""", unsafe_allow_html=True)

    basic_js = """
    <script>
    console.log("Basic JavaScript is running 1");
    </script>
    """
    st.markdown(basic_js, unsafe_allow_html=True)

    basic_js = """
    <script>
    console.log("Basic JavaScript is running 2");
    </script>
    """
    st.markdown(basic_js, unsafe_allow_html=True)

    # Handle the page refresh flag in Python
    print('st.session_state')
    print(st.session_state)

    if 'page_refreshed' not in st.session_state:
        print('page refresh not in session state -> session state.page refreshed = false')
        st.session_state.page_refreshed = False
        print(st.session_state)

    st.markdown(set_local_storage, unsafe_allow_html=True)
    st.markdown(check_local_storage, unsafe_allow_html=True)

    page_refresh_flag = st.session_state.page_refreshed

    st.write("""
    <script>
    console.log("check_page_refresh")
    const pageRefreshFlag = document.body.getAttribute('data-page-refresh');
    console.log(pageRefreshFlag)
    if (pageRefreshFlag === 'true') {
        console.log("pageRefreshFlag is true")
        console.log("page was refreshed")
        window.parent.postMessage({type: 'page-refresh'}. '*');
    else:
        console.log("page was not refreshed")
    }
    </script>""", unsafe_allow_html=True)

    st.write("""
    <script>
    window.addEventListener('message', (event) => {
        if (event.data.type === 'page-refresh') {
            console.log("event data type is pege_refresh in message listener")
            window.parent.document.querySelector('section[data-testid="stAppViewContainer"]').setAttribute('data-page-refreshed', 'true');
        }
    });
    </script>""", unsafe_allow_html=True)

    if page_refresh_flag:
        print('page refreshed if false in get page refreshed')
        delete_folder_function(st.session_state.session_number)
        st.session_state.page_refreshed = False

Thank you in advance!

1 Like