1

I am trying to write a library that will embed some JavaScript into a Jupyter notebook. The code works fine using %%javascript magic, but I want to embed the loading of the JavaScript into a library call. I found this SO post: Jupyter Notebook, Python: How to call a magic from within a function? but it only partially works.

The following code correctly runs the JavaScript alert:

from IPython.core.magics.display import Javascript
Javascript('alert("hello world")')

The following, however, does not work (nothing happens; no console errors):

from IPython.core.magics.display import Javascript

def foo():
    Javascript('alert("hello world")')
foo()

How do I embed a working call to Javascript within a function?

John
  • 2,012
  • 2
  • 21
  • 33

1 Answers1

1

Shoot. It's amazing how much more quickly your mind can work after posting to SO.

For posterity, the Javascript function works with Jupyter by returning the necessary code. In order to get my example working, the only change is to make foo return the result of Javascript(...). I was thinking of it as a void return with the work done within the function via some magical connection to the notebook. Not so! (Of course if this had been statically typed, I would known this and saved myself some time, but I digress.) Anwyay, the proper code is:

from IPython.core.magics.display import Javascript

def foo():
    return Javascript('alert("hello world")')
foo()
John
  • 2,012
  • 2
  • 21
  • 33
  • It may be similar to ruber duck debugging, but instead of solving the problem only for yourself, posting it here makes it useful to others, anyways, it is good that you found the solution, and quickly. – Eliâ Melfior Jul 16 '19 at 14:27