diff --git a/packages/core/src/sanitization/sanitization.ts b/packages/core/src/sanitization/sanitization.ts index f3f8cabec65..95bae73f90c 100644 --- a/packages/core/src/sanitization/sanitization.ts +++ b/packages/core/src/sanitization/sanitization.ts @@ -124,10 +124,12 @@ export function ɵɵsanitizeUrl(unsafeUrl: any): string { * A `url` sanitizer which only lets trusted `url`s through. * * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}. + * `null` and `undefined` are not considered unsafe and are mapped to an empty string, so that a + * resource URL binding can be cleared without having to provide a trusted placeholder value. * * @param unsafeResourceUrl untrusted `url`, typically from the user. - * @returns `url` string which is safe to bind to the `src` properties such as ``, because - * only trusted `url`s have been allowed to pass. + * @returns `url` string which is safe to bind to the `src` properties such as ``; + TestBed.overrideComponent(SecuredComponent, {set: {template}}); + const fixture = TestBed.createComponent(SecuredComponent); + + // The property is set to an empty string, which the browser treats as `about:blank`. + checkNullishResourceUrl(fixture, ''); + }); + + it('should allow binding null and undefined to resource URL attributes', () => { + const template = ``; + TestBed.overrideComponent(SecuredComponent, {set: {template}}); + const fixture = TestBed.createComponent(SecuredComponent); + + // Nullish attribute values remove the attribute without going through the sanitizer. + checkNullishResourceUrl(fixture, null); + }); + it('should escape unsafe attributes', () => { const template = `Link Title`; TestBed.overrideComponent(SecuredComponent, {set: {template}}); diff --git a/packages/core/test/sanitization/sanitization_spec.ts b/packages/core/test/sanitization/sanitization_spec.ts index c8d794fe4d8..0a5880256a8 100644 --- a/packages/core/test/sanitization/sanitization_spec.ts +++ b/packages/core/test/sanitization/sanitization_spec.ts @@ -91,6 +91,11 @@ describe('sanitization', () => { ).toEqual('javascript:true'); }); + it('should map null and undefined resourceUrls to an empty string', () => { + expect(ɵɵsanitizeResourceUrl(null).toString()).toEqual(''); + expect(ɵɵsanitizeResourceUrl(undefined).toString()).toEqual(''); + }); + it('should sanitize style', () => { expect(ɵɵsanitizeStyle('red')).toEqual('red'); expect(ɵɵsanitizeStyle(new Wrap('red'))).toEqual('red');