html - Angular Dom Sanitizer HTML 无法复制文本

标签 html angular copy sanitizer angular-dom-sanitizer

我使用 DomSanitizer 从数据库中清理我的 HTML 内容以显示在页面上。

<div [innerHtml]="safeHtml(article.text)"></div>

safeHtml 在哪里:
safeHtml(html){
    return this.sanitize.bypassSecurityTrustHtml(html);
}

它工作完美。但是我注意到在网页上显示时无法选择或复制此文本。否则,可以正常复制或选择正常字符串字段中显示的文本。

最佳答案

乍一看bypassSecurityTrustHtml()看起来是我们想要的,但文档警告不要使用这种方法。假设数据库中的内容不包含 <script> bypassSecurityTrustHtml 是错误的方法。它还可能导致插入的 html 中的文本不被选择/复制。

Bypass security and trust the given value to be safe HTML. Only use this when the bound HTML is unsafe (e.g. contains tags) and the code should be executed. The sanitizer will leave safe HTML intact, so in most situations this method should not be used.



<div [innerHtml]="article.text | keepHtml"></div>

import { Pipe, PipeTransform, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'keepHtml', pure: false })
export class EscapeHtmlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}

    transform(content) {
        return this.sanitizer.sanitize(SecurityContext.HTML, content);
    }
}


在特定情况下,可能需要禁用清理,例如,如果应用程序确实需要生成 javascript: 样式链接,其中包含动态值。用户可以通过使用 bypassSecurityTrust... 方法之一构造一个值,然后从模板绑定(bind)到该值来绕过安全性。

这些情况应该是非常罕见的,并且必须格外小心以避免创建跨站点脚本 (XSS) 安全漏洞!

使用 bypassSecurityTrust... 时,请确保尽可能早地调用该方法,并尽可能靠近值的来源,以便轻松验证其使用不会产生安全漏洞。

如果值是安全的,则不需要(也不推荐)绕过安全性,例如不以可疑协议(protocol)开头的 URL,或不包含危险代码的 HTML 片段。 sanitizer 保持安全值不变。

sanitize()

If value is trusted for the context, this method will unwrap the contained safe value and use it directly. Otherwise, value will be sanitized to be safe in the given context, for example by replacing URLs that have an unsafe protocol part (such as javascript:). The implementation is responsible to make sure that the value can definitely be safely used in the given context.

关于html - Angular Dom Sanitizer HTML 无法复制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799861/

相关文章:

c++ - 将指针而不是迭代器传递给 std::copy

Docker:当 Dockerfile 位于子目录中时使用 COPY

javascript - 水平 slider 上的标记

html - Div 在 IE8/7 中不可见...有时

javascript - ionic2 - 滚动触发

validation - angular2 自定义模板验证器具有过时值

css - 如何用Dart Angle 2 Material 设置 Material 扩展面板的样式

c++ - 如何生成嵌入所有文件的 C++ 安装程序?

Python + Selenium : How to switch to overlay

HTML 文件的图像未在 ios 应用程序中加载