How to inject Javascript into a streamlit dashboard element? Having difficulties

Hi! My Streamlit app generates a nice, interactive stock chart. The only issue is that the time axis gets slightly cut off at the bottom (see attached images). However, when I enter the following in the Chrome DevTools console:

document.querySelector('iframe').contentDocument.querySelector('tr:last-of-type').querySelectorAll('td[style]')[1].querySelector('div[style]').style.height = '130%'

—the time axis shifts upward and the problem is resolved.

But when I try embedding the same JavaScript snippet using st.markdown or st.components in my Streamlit code, it doesn’t have any effect when the app loads.

How can I get this JavaScript to actually run from within my Streamlit app?


import streamlit as st
from streamlit_lightweight_charts_ntf import renderLightweightCharts
import streamlit.components.v1 as components
import json
import numpy as np
import yfinance as yf
import pandas as pd
import pandas_ta as ta
import time

COLOR_BULL = 'rgba(38,166,154,0.9)' # #26a69a
COLOR_BEAR = 'rgba(239,83,80,0.9)'  # #ef5350

# Request historic pricing data via finance.yahoo.com API
df = yf.Ticker('AAPL').history(period='9mo')[['Open', 'High', 'Low', 'Close', 'Volume']]

# Some data wrangling to match required format
df = df.reset_index()
df.columns = ['time','open','high','low','close','volume']                  # rename columns
df['time'] = df['time'].dt.strftime('%Y-%m-%d')                             # Date to string

# export to JSON format
df['color'] = np.where(  df['open'] > df['close'], COLOR_BEAR, COLOR_BULL)  # bull or bear
candles = json.loads(df.to_json(orient = "records"))


st.subheader("Multipane Chart with Pandas")


chartMultipaneOptions = [{"height": 600,}]

seriesMultipaneChart = [
    {
        "type": 'Candlestick',
        "data": candles,
    },
]

renderLightweightCharts([
    {"chart": {"height": 600,},
        "series": seriesMultipaneChart}])

st.markdown and st.html don’t support scripting. You can use components, but st.components.v1.html is iframed, so your script needs to access the window’s parent’s document. For example: How would I add a JavaScript to the text_area so that it changes the function of the "tab" key? - #2 by mathcatsand

1 Like

@mathcatsand You’re a certified legend, thank you!

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