I have a div
which will receive a CSS background image from user chosen URL, like so:
background-image: url("/* user specified URL here*/")
How should I escape the URL so that it's safe to embed in the CSS? Is escaping the quotes enough?
const style = "background-image: url(\"" + CSS.escape(imageUrl) + "\")";
See https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape
It is an experimental new thing, but it seems to be quite well supported (as of 2021).
If you are setting the background url through JS, then the correct and safe ways is using encodeURI() and wrapping in quotes.
node.style.backgroundImage = 'url("' + encodeURI(url) + '")';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With