Gradio HTML component with javascript code don't work

hello @laro1

You canโ€™t load scripts via gr.HTML, but you can run a JavaScript function on page load and thus set your JavaScript code to globalThis, thus visible to the entire page


import gradio as gr

html = """
<html>
  <body>
    <h1>My First JavaScript</h1>
    <button type="testButton" onclick="testFn()"> Start </button>
    <p id="demo"></p>

  </body>
</html>
"""

scripts = """
async () => {
   // set testFn() function on globalThis, so you html onlclick can access it
    globalThis.testFn = () => {
      document.getElementById('demo').innerHTML = "Hello"
    }
}
"""

with gr.Blocks() as demo:   
    input_mic = gr.HTML(html)
    out_text  = gr.Textbox()
    # run script function on load,
    demo.load(None,None,None,_js=scripts)

if __name__ == "__main__":   
    demo.launch()

2 Likes