0

I am trying to deliver an SVG response with the help of NodeJS. This SVG has a small inline JavaScript code that dynamically calculates the width of the SVG. Everything works when the APIs are called directly using the browser. But when I use these APIs in GitHub's readme (to server SVGs in readmes) it's not allowing me to run this inline JavaScript code stored in SVG.

So when I asked this why custom headers for content-security-policy not working on github question, I got to know that github doesn't allow any inline JS, and we can't override Github's Content-Security-Policy to execute JS stored in SVGs.

So now I thought of executing the inline JavaScript on the server-side to calculate the SVG width and embed that in SVG. But the problem is how to execute this svg.setAttribute("width", svg.getBBox().width); at server side. As these SVGs are Template Literals on the server-side.

Questions:

Is there a way to calculate the width of SVG without rendering it on the server-side?
OR
Do I have to create a virtual DOM on the server-side to load the SVG in that DOM and then calculate the width?
OR
Is there a way to do this without JavaScript?

Can anyone help me out on how to get the dynamic width of SVG on the server-side?

Rahul
  • 47
  • 8
  • You either need a complete rendering engine (a headless browser) server-side or a custom library that will do the job for you. There are libs on npm, but I have never looked into them, so I can't tell you anything about their quality. – ccprog Dec 28 '20 at 12:18
  • You are probably going to have to use something like [Puppeteer](https://github.com/puppeteer/puppeteer). Or write a standalone program with something like [Batik](https://xmlgraphics.apache.org/batik/), that you can call from Node. – Paul LeBeau Dec 29 '20 at 08:06

0 Answers0