A couple things:
- You need to use
streamlit.components.v1.html
to execute JavaScript. - When you use components, it’s iframed, so you need to use
window.parent.document...
to select objects.
I modified your selectors so it works, but I’m not well-informed of the risks and best ways to accomplish this behavior, so there may be some other considerations for how best to structure the logic.
import streamlit as st
from streamlit.components.v1 import html
st.header("Assembly")
html("""
<script>
const textArea = window.parent.document.getElementsByClassName("st-key-text_area")[0].getElementsByTagName("textarea")[0];
textArea.addEventListener("keydown", function(event) {
if (event.key === "Tab") {
event.preventDefault();
const start = textArea.selectionStart;
const end = textArea.selectionEnd;
textArea.value = textArea.value.substring(0, start) + " " + textArea.value.substring(end);
textArea.selectionStart = textArea.selectionEnd = start + 4;
}
});
</script>
""")
with st.container(key="text_area"):
codigo = st.text_area("Digite seu código")