File size: 3,818 Bytes
9d6ac78
3a17f78
5967551
fc1a892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1337da7
 
 
 
b30a75c
5967551
 
3a17f78
5967551
 
 
 
3a17f78
5967551
 
ddbb47f
3a17f78
5967551
 
ddbb47f
5967551
3a17f78
5967551
 
 
 
 
9d6ac78
 
3a17f78
b30a75c
5967551
ddbb47f
3a17f78
5967551
3a17f78
5967551
b30a75c
3a17f78
5967551
ddbb47f
3a17f78
5967551
 
3a17f78
5967551
ddbb47f
5967551
 
 
ddbb47f
5967551
3a17f78
ddbb47f
5967551
b30a75c
5967551
 
b30a75c
ddbb47f
1337da7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import streamlit as st
from streamlit.components.v1 import html



from streamlit_cookies_controller import CookieController

st.set_page_config('Cookie QuickStart', 'πŸͺ', layout='wide')

controller = CookieController()

# Set a cookie
controller.set('cookie_name', 'testing')

# Get all cookies
cookies = controller.getAll()

# Get a cookie
cookie = controller.get('cookie_name')

# Remove a cookie
controller.remove('cookie_name')







# Debugging Headers and Cookies
st.write("Headers:", st.context.headers)
st.write("Cookies:", st.context.cookies)

# Define JavaScript code
javascript_code = """
<script>
    // Function to return a string
    function myJavaScriptFunction() {
        return "Hello from JavaScript!";
    }

    // Function to call and send data back to Python
    function callAndCapture() {
        const result = myJavaScriptFunction();
        // Send the result back to Streamlit
        window.parent.postMessage({ isStreamlitMessage: true, type: 'streamlit:js_return', data: result }, '*');
    }

    // Add an event listener to listen for messages from Streamlit
    window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'streamlit:buttonClick') {
            callAndCapture();
        }
    });
</script>
<button onclick="callAndCapture()">Run JavaScript Function</button>
"""

# Embed JavaScript into Streamlit app
html(javascript_code, height=300)

# Placeholder to display results
result_placeholder = st.empty()

# Add Streamlit button to trigger JavaScript function
if st.button("Call JavaScript Function"):
    st.write("Waiting for JavaScript response...")
    trigger_js = """
    <script>
    // Trigger the JavaScript function via a postMessage event
    window.parent.postMessage({ type: 'streamlit:buttonClick' }, '*');
    </script>
    """
    html(trigger_js, height=0)

# Add a listener for JavaScript responses
st.markdown(
    """
    <script>
    // Listen for messages from JavaScript
    window.addEventListener('message', (event) => {
        if (event.data && event.data.type === 'streamlit:js_return') {
            // Pass the data back to Streamlit as a new message
            const result = event.data.data;
            document.dispatchEvent(new CustomEvent('StreamlitResult', { detail: result }));
        }
    });

    // Dispatch data from CustomEvent to Streamlit
    document.addEventListener('StreamlitResult', (e) => {
        const data = e.detail;
        window.parent.postMessage({ type: 'streamlit:result', data: data }, '*');
    });
    </script>
    """,
    unsafe_allow_html=True,
)

# Use an iframe for communication
if "js_result" not in st.session_state:
    st.session_state["js_result"] = ""

try:
    # Listen for result data from JavaScript
    received_result = html(
        """
        <script>
        window.addEventListener('message', (event) => {
            if (event.data && event.data.type === 'streamlit:result') {
                const data = event.data.data;
                // Send the result back to Streamlit
                document.dispatchEvent(new CustomEvent('PythonReceivedResult', { detail: data }));
            }
        });

        document.addEventListener('PythonReceivedResult', (e) => {
            const received = e.detail;
            document.getElementById('result-placeholder').innerText = received;
        });
        </script>
        <div id="result-placeholder"></div>
        """,
        height=0,
    )

    # If there's a new result, update it in session state
    if received_result and received_result != st.session_state["js_result"]:
        st.session_state["js_result"] = received_result
        result_placeholder.write(f"Result from JavaScript: {received_result}")

except Exception as e:
    st.error(f"An error occurred: {e}")