简体   繁体   English

Angular 10 - 清理样式和脚本,以字符串形式提供

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

I am trying to figure out how DomSanitizer really works in Angular 10.我试图弄清楚DomSanitizer在 Angular 10 中是如何真正工作的。

I've been trying to sanitize the following CSS string without any luck:我一直在尝试清理以下 CSS 字符串,但没有任何运气:

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 .在上面的代码片段中, result常量变量总是等于testString What I expect to happen is : result should only contain color: blue;我期望发生的是result应该只包含color: blue; and the transform CSS property is filtered out from the string.并且从字符串中过滤掉了transform CSS 属性。

I have also tried to sanitize some JavaScript code, provided through a string like the following:我还尝试清理一些 JavaScript 代码,这些代码通过如下所示的字符串提供:

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 .但是,在此示例中, sanitize()函数会引发错误,并在脚本上下文中使用消息unsafe 值

What I expected to happen here is : result constant variable should be an empty string.我期望在这里发生的是result常量变量应该是一个空字符串。

You can place if Logic to check if its blue - and then else to return nothing or the desired data in return.您可以放置if Logic以检查其是否为蓝色 - 然后else不返回任何内容或返回所需的数据。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM