Angular 10 - Sanitizing style and script, provided in a string

1.4k views Asked by At

I am trying to figure out how DomSanitizer really works in Angular 10.

I've been trying to sanitize the following CSS string without any luck:

const testString = 'transform: rotate(70deg);color: blue;';
const result = this.sanitizer.sanitize(SecurityContext.STYLE, testString);

In the code snippet above, the result constant variable is always equal to testString. What I expect to happen is: result should only contain color: blue; and the transform CSS property is filtered out from the string.

I have also tried to sanitize some JavaScript code, provided through a string like the following:

const testString = 'alert("hacked!");console.log("logged");';
const result = this.sanitizer.sanitize(SecurityContext.SCRIPT, testString);

However, in this example, the sanitize() function throws an error with the message unsafe value used in a script context.

What I expected to happen here is: result constant variable should be an empty string.

1

There are 1 answers

2
chris burd On

You can place if Logic to check if its blue - and then else to return nothing or the desired data in return.

if(testString==='blue'){
const result = this.sanitizer.sanitize(SecurityContext.STYLE, testString);

} else {
console.log('whatever you like')
}