n-riesco / ijavascript

IJavascript is a javascript kernel for the Jupyter notebook
Other
2.18k stars 187 forks source link

SVG image with scripts #266

Closed frank-zsy closed 2 years ago

frank-zsy commented 2 years ago

Hello, I don't know if this is the right place to ask the question but I just can not find better.

I am using Jupyter Notebook with Node.js kernel provided by this repository.

And I am trying to render an SVG file in the notebook with some build-in scripts to generate the image in dynamic way just like this file, there is some code in onSvgLoad function which works fine in browser.

But the notebook seems not run the code and can not render any dynamic elements generated by the code.

Is there any way like plugins or packages which can support SVG image with code?

Very thanks to your help.

n-riesco commented 2 years ago

This is actually a security issue.

The Jupyter notebook (and other clients) strip JavaScript inside <svg> tags.

There is a way to work around this. Move all your JavaScript out of the <svg> tag, use setTimeout instead of onload,and use $$.html instead of $$.svg. For example:

$$.html(`
<svg id='mySvg'><rect width=80 height=80 style='fill: orange;'/></svg>
<script>
function sayHi() {
    if(document.getElementById('mySvg')) alert('Hi!')
    else setTimeout(sayHi, 100);
}
sayHi();
</script>
`)
frank-zsy commented 2 years ago

Thanks for your reply.

So the mechanism is built-in with Jupyter notebook and can not bypass by any plugin?

If this is the situation maybe we need to implement the SVG twice in different ways to do the trick.

n-riesco commented 2 years ago

There's an extension for JavaScript. See here. I guess the same could be done for SVG.

frank-zsy commented 2 years ago

Thank you very much but I am very new to Jupyter so I may use the way you suggest before.

I will close this issue now~