Import external JS scripts in Google Colab html

Viewed 3590

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 ()".

2 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>
  """)

Lines like script src="content/drive... won't work. The reason is that your Drive files are present on the backend VM executing your code. But, using a <script> tag is going to be resolved by your browser against the current base origin, which is colab.research.google.com, which doesn't serve your Drive files.

There are some recipes for serving local files in the advanced outputs example here:

https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT

Related