How to pass variables from javascript to python in Jupyter?

This is how I made your code work: enter image description here

or even simpler:

enter image description here


from IPython.display import HTML
HTML('''
<script type="text/javascript">
    IPython.notebook.kernel.execute("foo=11")
</script>
 ''')
from time import sleep
sleep(3)
print(foo)

The reason this works is the HTML takes some time to work and you print it even before the value is set. With sleep, the wait time of 3s seems to be enough and the variable gets assigned.


The problem here is that the HTML object is not the last one in the cell. So it is ignored in the same way any other value without print is not shown, unless it is the last one in the cell. If you execute a cell with the next code, you won't see any alert window.

HTML('''
    <script type="text/javascript">
        alert("hello")
    </script>
''')
print("hello")

Ensure that the last object in the cell is the HTML object and you will see the alert window.

HTML('''
    <script type="text/javascript">
        alert("hello")
    </script>
''')

That's why the examples of Anthony Perot work, they are separated cells. This should also work:

HTML and print in separated cells