Injecting Javascript to already existing component streamLit

Hi,

I am trying to inject Javascript to streamlit usi that will help make sure that streamlit will stop scroll as new output is stream from LLM.

But for some reason whenever I trying getting an element from the DOM(stMain). I get null.

So how do I inject javascript into streamlit in order to change already present components.

Code I am trying to use:

def InjectJs(js: str, atEveryRerun: bool = False) -> None:
    """Injects the specified JS code into the Streamlit page."""
    
    components.html(
        "<script type='text/javascript'>\n" +

        # If the code should be injected on every rerun, add a random comment
        (f"// random number: {rd.random()}\n" if atEveryRerun else "") +

        # JS code to get the current iframe element (updated for stMain)
        "document.addEventListener('DOMContentLoaded', function() {\n" +
        "    const container = document.querySelector('.stMain'); // Find the main container\n" +
        "    if (container) {\n" +
        "        let lastScrollTop = container.scrollTop; // Store last scroll position\n" +
        "        Object.defineProperty(container, 'scrollTop', {\n" +
        "            set: function(value) {\n" +
        "                if (container.scrollHeight === container.scrollTop + container.clientHeight) {\n" +
        "                    lastScrollTop = container.scrollTop;\n" +
        "                } else {\n" +
        "                    container.scrollTop = lastScrollTop;\n" +
        "                }\n" +
        "            }\n" +
        "        });\n" +
        "        container.addEventListener('scroll', function() {\n" +
        "            lastScrollTop = container.scrollTop;\n" +
        "        });\n" +
        "    }\n" +
        "});\n" +
        js + "\n</script>",
        height=0,
    )

Components are iframed. You need to break out of the iframe to get to other app elements (window.parent.document). Like this: Need to automatically go at the top of the page - #4 by mathcatsand

1 Like

Hi thanks now the code works perfectly

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.