awacke1 commited on
Commit
3a17f78
Β·
verified Β·
1 Parent(s): 5967551

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -37
app.py CHANGED
@@ -1,23 +1,23 @@
1
  import streamlit as st
 
2
 
3
- # Define the JavaScript to be embedded
4
  javascript_code = """
5
  <script>
 
6
  function myJavaScriptFunction() {
7
- // Function to return a string
8
  return "Hello from JavaScript!";
9
  }
10
 
11
- // Function to be called on button click; uses window.alert to display the return value
12
  function callAndCapture() {
13
  const result = myJavaScriptFunction();
14
- // Use Streamlit's via the streamlit:component event to send data back to Python
15
- window.parent.postMessage({isStreamlitMessage: true, type: 'streamlit:component', data: result}, '*');
16
  }
17
 
18
- // Add an event listener to handle messages from the iframe or parent window.
19
  window.addEventListener('message', function(event) {
20
- if (event.data.type === 'streamlit:buttonClick') {
21
  callAndCapture();
22
  }
23
  });
@@ -25,35 +25,30 @@ javascript_code = """
25
  <button onclick="callAndCapture()">Run JavaScript Function</button>
26
  """
27
 
28
- # Create a container for HTML/JS script
29
- html_container = st.empty()
30
- html_container.html(javascript_code + "<div id='returned_value'></div>", height=300)
31
 
32
- # Create a placeholder message
33
- message_placeholder = st.empty()
34
 
35
- # Add a button in Streamlit to send a message to the iframe to call JavaScript
36
  if st.button("Call JavaScript Function"):
37
- js = """
38
  <script>
39
- window.parent.postMessage({type: "streamlit:buttonClick"}, "*");
40
  </script>
41
  """
42
- html_container.html(javascript_code + js + "<div id='returned_value'></div>", height=300)
43
 
44
- # Future-proofing to listen for messages from the JavaScript side
45
- if "js_result" not in st.session_state:
46
- st.session_state["js_result"] = ""
47
-
48
- # Handle messages from JavaScript
49
  st.markdown(
50
  """
51
  <script>
52
  window.addEventListener('message', (event) => {
53
- if (event.data && event.data.isStreamlitMessage) {
54
  const result = event.data.data;
55
- // Reflect the result back to the Python script
56
- window.parent.postMessage({type: 'streamlit:component_with_result', data: result}, '*');
57
  }
58
  });
59
  </script>
@@ -61,26 +56,27 @@ st.markdown(
61
  unsafe_allow_html=True,
62
  )
63
 
64
- # Python-side listener to write the result to the placeholder
 
 
 
65
  try:
66
- import streamlit.components.v1 as components
67
- messages = components.html(
68
  """
69
  <script>
70
  window.addEventListener('message', (event) => {
71
- if (event.data.type === 'streamlit:component_with_result') {
72
- window.parent.postMessage(event.data.data, '*');
 
73
  }
74
  });
75
  </script>
76
  """,
77
  height=0,
78
  )
79
- if_messages_received = messages._deserialize()
80
- if if_messages_received and if_messages_received != st.session_state["js_result"]:
81
- st.session_state["js_result"] = if_messages_received
82
- message_placeholder.markdown("_" + if_messages_received + "_")
83
- except:
84
- pass
85
-
86
- st.session_state["js_result"]
 
1
  import streamlit as st
2
+ from streamlit.components.v1 import html
3
 
4
+ # Define JavaScript code as a single script
5
  javascript_code = """
6
  <script>
7
+ // Function to return a string
8
  function myJavaScriptFunction() {
 
9
  return "Hello from JavaScript!";
10
  }
11
 
12
+ // Function to call and send data back to Python
13
  function callAndCapture() {
14
  const result = myJavaScriptFunction();
15
+ window.parent.postMessage({ isStreamlitMessage: true, type: 'streamlit:js_return', data: result }, '*');
 
16
  }
17
 
18
+ // Add event listener to handle messages from Streamlit
19
  window.addEventListener('message', function(event) {
20
+ if (event.data && event.data.type === 'streamlit:buttonClick') {
21
  callAndCapture();
22
  }
23
  });
 
25
  <button onclick="callAndCapture()">Run JavaScript Function</button>
26
  """
27
 
28
+ # Embed JavaScript into Streamlit app
29
+ html_container = html(javascript_code, height=300)
 
30
 
31
+ # Placeholder for displaying results
32
+ result_placeholder = st.empty()
33
 
34
+ # Add Streamlit button to trigger JavaScript function
35
  if st.button("Call JavaScript Function"):
36
+ trigger_js = """
37
  <script>
38
+ window.parent.postMessage({ type: 'streamlit:buttonClick' }, '*');
39
  </script>
40
  """
41
+ html(trigger_js, height=0)
42
 
43
+ # Listener for JavaScript messages
 
 
 
 
44
  st.markdown(
45
  """
46
  <script>
47
  window.addEventListener('message', (event) => {
48
+ if (event.data && event.data.type === 'streamlit:js_return') {
49
  const result = event.data.data;
50
+ // Reflect the result back to Streamlit
51
+ window.parent.postMessage({ type: 'streamlit:python_side', data: result }, '*');
52
  }
53
  });
54
  </script>
 
56
  unsafe_allow_html=True,
57
  )
58
 
59
+ # Handle the result sent from JavaScript
60
+ if "js_result" not in st.session_state:
61
+ st.session_state["js_result"] = ""
62
+
63
  try:
64
+ received_result = html(
 
65
  """
66
  <script>
67
  window.addEventListener('message', (event) => {
68
+ if (event.data && event.data.type === 'streamlit:python_side') {
69
+ const data = event.data.data;
70
+ document.dispatchEvent(new CustomEvent('StreamlitResult', { detail: data }));
71
  }
72
  });
73
  </script>
74
  """,
75
  height=0,
76
  )
77
+ # Capture and update the session state
78
+ if received_result != st.session_state["js_result"]:
79
+ st.session_state["js_result"] = received_result
80
+ result_placeholder.write(f"Result from JavaScript: {received_result}")
81
+ except Exception as e:
82
+ st.error(f"An error occurred: {e}")