How to bind JS-to-python variable binding in jupyter notebooks with `IPython` in VsCode?

We use the IPython library to enable JS-to-python binding (have JS to “talk back” to python) in jupyter notebooks.
Our code works in jupyter notebooks in the browser, but not in VsCode’s jupyter notebooks.

Here’s a simple example to reproduce the problem.

from IPython.display import display, HTML, Javascript

js_code = """
function sendToPython(){
    var data = document.querySelector("#myInput").value;
    var kernel = IPython.notebook.kernel;
    kernel.execute("data_from_js="" + data + """);
}

document.querySelector("#myButton").addEventListener("click", function(){
    sendToPython();
});
"""

data_from_js = None

HTML_code = """
<input type="text" id="myInput" placeholder="Enter some text">
<button id="myButton">Submit</button>
<script type="text/Javascript">{}</script>
""".format(js_code)

display(HTML(HTML_code))

This will display a text element and a submit button.
Enter “hello” in input text field, then click “Submit” button.
Then, in a different cell, if you do print(data_from_js), you should get “hello”.

And we do, in a browser-based notebook.
But in VsCode the data_from_js variables remains untouched:

The developer tools console says “IPython is not defined”:

For more details, and attempts at solving this problem, see the Getting JS to talk back to Python jy discussion.

Leave a Comment