I'd like to insert some user generated css into the head
of my html using javascript. The issue is that when I escape certain characters break the CSS.
For example:
let css = `
@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
body { font-family: "Roboto", sans-serif; }
`,
style = document.createElement('style');
style.type = 'text/css';
document.head.appendChild(style);
css = escape(css);
style.appendChild( document.createTextNode( css ) );
outputs:
<style type="text/css" id="custom-theme-styles">
@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
body { font-family: "Roboto", sans-serif !important; }
</style>
As you can see the the single and double quotes produce '
and "
respectively. The ampersand in the query string converts to &
. I could also see issues using the css child combinator (>).
Is there a way to escape the css so that it doesn't break and renders securely? It feels like a bad idea, but if I don't escape the css, is this even a security concern? I could be wrong but I don't think a <script>
tag inside a <style>
tag would execute. Are there any other vulnerabilities I'm missing with not escaping the css?