How do I avoid image urls for CSS?
Is holding quotes enough?
No, you should also worry about backslashes and newlines.
Here is the CSS grammar for the double quoted URI: http://www.w3.org/TR/CSS21/grammar.html#scanner
"([^\n\r\f\\"]|\\{nl}|{escape})"
where {nl}
-
\n|\r\n|\r|\f
and {escape}
is a backslash character. So trailing backslashes will break your CSS. Unescaped newline also.
I would highly recommend removing all spaces and finally exit "
and\
source to share
Since the user data that needs to be inserted into the CSS can be thought of as a URL, not just a string, you only need to make sure it is URL encoded correctly.
This is safe because a well-formed URL does not contain characters that are unsafe in CSS strings; other than apostrophe ( '
), which is not a problem if you use double quotes for your CSS string:url("...")
An easy way to do this is to URL-encode all characters that are not "reserved" or "unconditional" in URLs. According to RFC 3986 , these will be all characters except the following:
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # [ ]
This is what Mārtiņš Briedis JavaScriptencodeURI()
does in answer . (With one exception: encodeURI()
encodes [
and ]
, which is mostly irrelevant.)
In addition to this, you can only think about resolving URLs starting with https:
or data:
. By doing this, you can prevent mixed content warnings if the page is served over HTTPS, and also avoid the problem javascript:
Alexander O'Mara commented .
There may be other parsing and validation of the URL that you want to do, but that is outside the scope of this question.
If you need to insert user data into a CSS string that cannot be seen as a URL, you will need to do CSS backslash escaping . See user123444555621 for details .
source to share