/** * Creates a SafeUrl object from the given {@code url}, validating that the input string matches * a pattern of commonly used safe URLs. If {@code url} fails validation, this method returns a * SafeUrl, {@link SafeUrl#INNOCUOUS}, which contains an innocuous string, * {@link SafeUrl#INNOCUOUS_STRING}. * * <p>Specifically, {@code url} may be a URL with any of the default safe schemes (http, https, * ftp, mailto), or a relative URL (i.e., a URL without a scheme; specifically, a scheme-relative, * absolute-path-relative, or path-relative URL). * * @see http://url.spec.whatwg.org/#concept-relative-url */ public static SafeUrl sanitize(String url) { return sanitize(url, EMPTY_CUSTOM_SCHEMES); }
/** * Appends a {@code url} value to the {@code background-image} property, if necessary inserting * a leading comma. The {@code url} value will be inserted inside a {@code url} function call. * * <p>The {@code url} is validated as safe, as determined by {@link SafeUrls#sanitize(String)}. * It also percent-encoded to prevent it from interefering with the structure of the surrounding * CSS. * * <p>TODO(mlourenco): The right thing to do would be to CSS-escape but percent-encoding is * easier for now because we don't have a CSS-escaper. As URLs in CSS are likely to point to * domains we control it seems extremely unlikely that this will break anything. * * @see "http://dev.w3.org/csswg/css-backgrounds/#background-image" */ public SafeStyleBuilder backgroundImageAppendUrl(String url) { url = SafeUrls.sanitize(url).getSafeUrlString(); try { url = ESCAPER_BACKGROUND_IMAGE.escape(url); } catch (IllegalArgumentException e) { // Happens if url contains invalid surrogate sequences. url = INNOCUOUS_PROPERTY_STRING; } String urlValue = "url(" + url + ")"; appendToProperty("background-image", urlValue); return this; }