是否可以在 Angular2 上清理允许某些标签的 HTML 字符串? [英] Is possible Sanitize on Angular2 a HTML string allowing certaing tags?
问题描述
我正在清理当前的 html(字符串值),我想知道是否可以只允许某些属性.在这个例子中,字符串应该只保留id"属性.像这样:
I am sanitizing the current html (string value), I want to know if is possible only allow certains attributes. In this example the string only should keep the "id" attribute. Like this:
<h1 id="header">DomSanitizer</h1><script>ourSafeCode()</script>');
这是我的组件的一个例子.
This is an example of my component.
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>') ;
}
}
但相反,我从字符串中获取了所有属性,我正在考虑定期进行类似的操作.但是我想知道我是否可以过滤属性(我是菜鸟).
But instead I am getting all the attributes from the string, I was thiking on a regular expersion o something like that. But I want to know if I can filter the attributes (I am noob).
推荐答案
您可以通过覆盖来向 sanitizer 添加自定义逻辑.这是超级hacky,但它看起来像:
You can add custom logic to the sanitizer by overriding it. It's super hacky but it looks like:
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
...
}
}
}
这篇关于是否可以在 Angular2 上清理允许某些标签的 HTML 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!