Summary
I created a component that downloads a widget and injects it into the dom of its parent after clicking a button. The script that is being injected into DOM prints some messages that I want to capture. How do I capture the console printed by that widget.
Steps to reproduce
My component is as follows
Code snippet:
import { Streamlit, RenderData } from "streamlit-component-lib"
const span = document.body.appendChild(document.createElement("span"))
let script = document.body.appendChild(document.createElement('script') as HTMLScriptElement);;
const textNode = span.appendChild(document.createTextNode(""))
const button = span.appendChild(document.createElement("button"))
button.textContent = "Download!"
async function getSetupScript(id: string) {
let url: string = `https://mydomain.com//${id}//setup.js`;
try {
const { status, data } = await axios.get(url);
console.log(`trying to get setup script from ${url}`)
console.log(`HTTP Status ${status}`)
if (status === 200) {
let data_ = data as string
console.log(data_)
script.innerHTML = data_ as string;
// console.log(data)
script.id = "my_widget"
getStatus(id);
return true;
}
} catch (exception) {
return false;
}
}
async function getStatus(id: string) {
let url: string = `https://mydomain.com/widget/status`;
try {
const { status, data } = await axios.get(url, {
params: { id: id }, headers: {
'Content-Type': 'application/json'
}
});
console.log(`trying to get status of widget from ${url}`)
console.log(`HTTP Status ${status}`)
if (status === 200) {
const sessionInfo = {
"StateSuccessful": true
}
console.log(JSON.stringify(sessionInfo, null, 4))
}
} catch (exception) {
console.log(exception);
}
}
let global_id: string = "";
button.onclick = function (): void {
// Streamlit via `Streamlit.setComponentValue`.
if (global_id) {
getSetupScript(global_id).then((value) => {
Streamlit.setComponentValue(value);
});
} else {
console.log("no download")
}
}
/**
* The component's render function. This will be called immediately after
* the component is initially loaded, and then again every time the
* component gets new data from Python.
*/
function onRender(event: Event): void {
const data = (event as CustomEvent<RenderData>).detail
const { id } = data.args;
global_id = id;
Streamlit.setFrameHeight()
}
// Attach our `onRender` handler to Streamlit's render event.
Streamlit.events.addEventListener(Streamlit.RENDER_EVENT, onRender)
// Tell Streamlit we're ready to start receiving data. We won't get our
// first RENDER_EVENT until we call this function.
Streamlit.setComponentReady()
Streamlit.setFrameHeight()
This is working, however, I am new to TS and I don’t know how to capture the console that this injected script is generating to return as an object instead of a boolean (currently returns a boolean).
Or if I can add a listener, and every time I capture something in the console, I can parse and return only in cases my parsing success.