Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import external JS scripts in Google Colab html

I am having a hard time importing my custom external JS files to Google Colab. I work with html + js, following this workflow:

1 / imports

from IPython.display import HTML, SVG
from IPython.core.magic import register_cell_magic

2 / mount drive

from google.colab import drive
drive.mount('/content/drive')

3 / html

@register_cell_magic
def dojs(line, src):
  return HTML(f"""
  <canvas id="renderCanvas" touch-action="none" width="1280px" height="720px"></canvas> 
  <script src="content/drive/My Drive/Colab Notebooks/files/testJavascript.js"></script>
  <script>
  {src} 
  </script>
  """)

4 / js

%%dojs
//...trying to use functions from testJavascript.js

Maybe it's really trivial how to do this but I'm new at Colab. I get "Failed to load resource: the server responded with a status of 500 ()".

like image 852
des Avatar asked Jan 17 '19 13:01

des


People also ask

Can we code HTML in Google Colab?

HTML. HTML is incredibly easy to display in Google Colab. Just run something like: And see the results!

How do I run JavaScript on Google Colab?

To insert and run the JavaScript snippets, please hit F12 on a browser of your choice to open the console. Then paste the JavaScript snippet into the command window and press enter. Subsequently the browser will run the code to automate Google Colab by simulating button clicks.


1 Answers

You need to put your JS file in here:

/usr/local/share/jupyter/nbextensions/google.colab/

Then it can be access through the path

/nbextensions/google.colab/

In your case, you need to copy your js file there:

!cp /content/drive/My\ Drive/Colab\ Notebooks/files/testJavascript.js \
    /usr/local/share/jupyter/nbextensions/google.colab/

Then change dojs() to be

@register_cell_magic
def dojs(line, src):
  return HTML(f"""
  <canvas id="renderCanvas" touch-action="none" width="1280px" height="720px"></canvas> 
  <script src="/nbextensions/google.colab/testJavascript.js"></script>
  <script>
  {src} 
  </script>
  """)
like image 96
korakot Avatar answered Sep 22 '22 10:09

korakot