Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Shut down the session after closing the browser tab by the user #8545

@Anna050689

Description

@Anna050689

Checklist

  • I have searched the existing issues for similar feature requests.
  • I added a descriptive title and summary to this issue.

Summary

I want to implement the mechanism to detect the user exit after closing the tab and shut down the session on the backend side. I used the solution provided in the streamlit discussion - https://discuss.streamlit.io/t/detecting-user-exit-browser-tab-closed-session-end/62066/2

My code snippet is the next -

import threading

from streamlit.runtime.scriptrunner import add_script_run_ctx
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
from streamlit.runtime import get_instance


def heart_beat():
    """
    Heartbeat function to track whether the session is alive
    """
    thread = threading.Timer(interval=2, function=heart_beat)

    # insert context to the current thread, needed for
    # getting session specific attributes like st.session_state

    add_script_run_ctx(thread)

    # context is required to get session_id of the calling
    # thread (which would be the script thread)
    ctx = get_script_run_ctx()

    # this is the main runtime, contains all the sessions
    runtime = get_instance()

    if runtime.is_active_session(session_id=ctx.session_id):
        thread.start()
    else:
        return


if __name__ == "__main__":
    heart_beat()

Is it possible to shut down the session on the backend side?

Why?

It's important to have more controlled behavior, as our application will potentially interact with multiple users.

How?

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:backendRelated to Python backendtype:enhancementRequests for feature enhancements or new features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions