As a part of a project, I need to embedd some javascripts inside an IPython module. This is what I want to do:
from IPython.display import display,Javascript
Javascript('echo("sdfds");',lib='/home/student/Gl.js')
My Gl.js looks like this
function echo(a){
alert(a);
}
Is there some way so that I can embed "Gl.js" and other such external scripts inside the notebook, such that I dont have to include them as 'lib' argument everytime I try to execute some Javascript code which requires to that library.
Not out of the box by installing a package, at least for now. The way to do it is to use
custom.js
and jQuerygetScript
to inject the js into the notebook.I explicitly stay vague on how to do it, as it is a dev feature changing from time to time.
What you should know is that the
static
folder in user profile ismerged
with webserver static assets allowing you to access any file that are in this folder by asking for the right url.Also this question has been asked a few hours ago on IPython weekly video "lab meeting" broadcasted live and disponible on youtube (you might have a longer answer), I've opened discussion with the author of the question here
As a very short-term solution, you can make use of the IPython
display()
andHTML()
functions to inject some JavaScript into the page.Although I do not recommend this over the official
custom.js
method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.For some reason, I have problems with IPython.display.Javascript. Here is my alternative, which can handle both importing external .js files and running custom code:
Usage is as follows:
I've been fighting with this problem for several days now, here's something that looks like it works; buyer beware though, this is a minimal working solution and it's neither pretty nor optimal - a nicer solution would be very welcome!
First, in
.ipython/<profile>/static/custom/myScript.js
, we do some require.js magic:Copy this pattern for as many functions as you like. Then, in
.ipython/<profile>/static/custom/custom.js
, drag those out into something persistent:Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like
should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this (plz devs can we plz have
$.getScript('/static/custom/util.js');
incustom.js
to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!Embedding D3 in an IPython Notebook
To summarize the code.
Import the script:
Add an element like this:
Or this:
IPython Notebook: Javascript/Python Bi-directional Communication
A more extensive post explaining how to access Python variables in JavaScript and vice versa.