Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Can we use javascript with svg files in Chrome extensions?

65 views
Skip to first unread message

Mythical 5th

unread,
Mar 15, 2025, 7:09:09 PMMar 15
to Chromium Extensions
I've been trying to incorporate a dynamic SVG image into my Chrome extension. The code for the svg file and the javascript file are below, and they work when I open the svg file in Chrome outside of an extension. But when I try to load them in a page within my extension, the javascript is not being run.

I'm not sure if I need something in my CSP, or if this simply is not supported; there is nothing in the console. Any help would be appreciated.


rect.svg:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
  height="32" width="32"
  viewBox="0 0 32 32" version="1.1">
<rect x="0" y="0" width="32" height="32" fill="black"></rect>
<script href="rect.js"></script>
</svg>



rect.js:

document.querySelector("rect").style.fill="red";


al

unread,
Mar 15, 2025, 8:56:13 PMMar 15
to Chromium Extensions, Mythical 5th
If you're embedding it via an <img> tag, then it won't work as images aren't scriptable.

To quote the linked SO answer 
Basically, SVG when used in an image context emulates raster images. Raster images aren't scriptable so neither is SVG when it is used in that way.

However, looking at the rest of the answer and other comments, it looks like it should be possible with <embed> or similar tags.
So it just depends on how you embed the SVG.

Mythical 5th

unread,
Mar 15, 2025, 10:05:10 PMMar 15
to Chromium Extensions, al, Mythical 5th
Thanks, that answer makes a lot of sense. I've got it working now.
Reply all
Reply to author
Forward
0 new messages