IPython: Adding Javascript scripts to IPython notebook

风格不统一 提交于 2019-11-30 02:27:00

As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.

from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))

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.

Embedding D3 in an IPython Notebook

To summarize the code.

Import the script:

%%javascript
require.config({
  paths: {
      d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'
  }
});

Add an element like this:

%%javascript
element.append("<div id='chart1'></div>");

Or this:

from IPython.display import Javascript
#runs arbitrary javascript, client-side
Javascript("""
           window.vizObj={};
           """.format(df.to_json()))

IPython Notebook: Javascript/Python Bi-directional Communication

A more extensive post explaining how to access Python variables in JavaScript and vice versa.

Not out of the box by installing a package, at least for now. The way to do it is to use custom.js and jQuery getScript 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 is merged 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

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:

define(function(){

    var foo = function(){
            console.log('bar');
        }

    return {
        foo : foo
    }
});

Copy this pattern for as many functions as you like. Then, in .ipython/<profile>/static/custom/custom.js, drag those out into something persistent:

$([IPython.events]).on('notebook_loaded.Notebook', function(){

    require(['custom/myScript'], function(custom){
        window.foo = custom.foo;
    } );

});

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

%%javascript

foo();

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'); in custom.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!

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:

from IPython.display import display, HTML

def javascript(*st,file=None):
    if len(st) == 1 and file is None:
        s = st[0]
    elif len(st) == 0 and file is not None:
        s = open(file).read()
    else:
        raise ValueError('Pass either a string or file=.')
    display(HTML("<script type='text/javascript'>" + s + "</script>"))

Usage is as follows:

javascript('alert("hi")')
javascript(file='Gl.js')
javascript('echo("sdfds")')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!