Skip to content

Open In Colab

Running JavaScript in Jupyter Notebook

import random
from IPython.display import display, Javascript, HTML, clear_output

unique_id = str(random.randint(100000, 999999))

display(Javascript(
    '''
    var id = '%(unique_id)s';
    // Make a new global function with a unique name, to prevent collisions with past
    // executions of this cell (since JS state is reused).
    window['render_' + id] = function() {
        // Put data fetching function here.
        // $('#' + id).text('Hello at ' + new Date());

        $.getJSON('https://api.db-ip.com/v2/free/self', function(data) {
          // console.log(JSON.stringify(data, null, 2));
          $('#' + id).text(JSON.stringify(data, null, 2));
        });

    }
    // See if the `HTML` block executed first, and if so trigger the render.
    if ($('#' + id).length) {
        window['render_' + id]();
    }
    ''' % dict(unique_id=unique_id)
    # Use % instead of .format since the latter requires {{ and }} escaping.
))

clear_output()

display(HTML(
    '''
    <div id="%(unique_id)s"></div>
    <!-- When this script block executes, the <div> is ready for data. -->
    <script type="text/javascript">
        var id = '%(unique_id)s';
        // See if the `Javascript` block executed first, and if so trigger the render.
        if (window['render_' + id]) {
            window['render_' + id]();
        }
    </script>
    ''' % {'unique_id': unique_id}
))
# Test