带有超链接的 Angular 5 DomSanitizer

use*_*798 7 html hyperlink ckeditor angular

我正在使用 WYSIWYG 编辑器(CKEditor)并尝试使用 Angular 5 呈现内容。

我想弄清楚的是在 Angular 5 中使用 DomSanitizer 的正确方法。我面临的问题是超链接在生成的经过消毒的 HTML 中不起作用(不可“点击”)。

我正在使用以下 Typescript 代码返回一个 safeHtml 内容:

 public getSafeContent(): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(this.page.content);
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式在我的模板中使用它:

<div [innerHTML]="getSafeContent()"></div>
Run Code Online (Sandbox Code Playgroud)

这将呈现具有完整内联样式的 HTML,但超链接将不起作用。

我尝试这样做:

public getSafeContent(): SafeHtml {
    return this.sanitizer.sanitize(SecurityContext.HTML, this.page.content);
}
Run Code Online (Sandbox Code Playgroud)

这导致超链接实际上有效,但内联样式无效。

有没有办法让样式和超链接都与经过消毒的内容一起使用?

更新

这是页面在 Chrome 开发工具中的样子:

<div _ngcontent-c22="" class="row">
   <div _ngcontent-c22="" class="col-lg-12">

        <div _ngcontent-c22="">
            <p><a href="http://www.google.com">google</a></p>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

并且谷歌链接不可点击。

Tim*_*ter 2

bypassSecurityTrustHtml允许<script>在内容中添加标签。对于您需要的 URL bypassSecurityTrustUrl。请参阅此处:https ://angular.io/api/platform-b​​rowser/DomSanitizer#bypassSecurityTrustUrl 。

我从来没有尝试过堆叠这些bypassXXX方法,所以我不知道你是否可以做这样的事情bypassSecurityTrustUrl(bypassSecurityTrustHtml(myContent)),但我猜可能不能,因为每个方法都接受一个字符串,但返回一个对象(类型为SafeHtml/SafeUrl),所以它不能使用作为需要字符串的堆栈函数调用的输入。

因此,您可能需要解析内容,将每个 URL 传递到 中bypassSecurityTrustUrl,然后再次将所有内容组合在一起。

更新

我刚刚看了消毒方法。我还没有尝试过这个,但类似这样的方法可能会起作用:

this.sanitizer.sanitize(SecurityContext.HTML, this.sanitizer.bypassSecurityTrustUrl(myContent));
Run Code Online (Sandbox Code Playgroud)

因为sanitize可以将 aSafeValue作为输入。内部bypassSecurityTrustUrl清理 URL 并返回一个SafeUrl,它被外部清理解包并用作输入以使其 HTML 安全。就像我说的,我还没有尝试过,但理论上看起来不错......