我正在清理当前的html(字符串值),我想知道是否可能只允许某些属性。在这个例子中,字符串只能保留" id"属性。像这样:
<h1 id="header">DomSanitizer</h1><script>ourSafeCode()</script>');
这是我的组件的一个例子。
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div [innerHtml]="html"></div>
`,
})
export class App {
constructor(private sanitizer: DomSanitizer) {
this.html = sanitizer.bypassSecurityTrustHtml('<h1 id="header" class="headerClass" style="background-color: red" >DomSanitizer</h1><script>ourSafeCode()</script>') ;
}
}
但是我得到了字符串中的所有属性,我正在经常出现这样的事情。但我想知道我是否可以过滤属性(我是菜鸟)。
答案 0 :(得分:0)
您可以通过覆盖来将自定义逻辑添加到 sanitizer。这是超级hacky,但它看起来像:
class Something {
constructor(sanitize: DomSanitizer) {
sanitize.sanitize = function(context: SecurityContext, value: SafeValue | string | null) {
// sanitize the string first because we still want to be secure
const res = (sanitize as any).__proto__.sanitize.call(sanitize as any, context, value) || '';
// match any attributes you don't want (or do want) and remove them
...
}
}
}