【问题标题】:How to set or override target= "_blank" in anchor tag in 'sanitize-html' ?如何在“sanitize-html”的锚标记中设置或覆盖 target=“_blank”?
【发布时间】:2018-05-11 07:04:34
【问题描述】:

我在我的项目中使用sanitize-html。假设我收到一封带有锚标签的邮件,如下所示: this is to test something <a href="https://www.google.com/">open google</a>

这封邮件出现在我的邮箱中,如下所示: this is to test something open google

在同一标签中打开 google.com。但是我需要在新标签页中打开。 这是我的代码。

__html = sanitizeHTML(children, {
        allowedTags: sanitizeHTML.defaults.allowedTags.concat([ 'img' ]),
        allowedAttributes: {
          '*': [ 'href', 'align', 'alt', 'center', 'bgcolor', 'style', 'width' ],
          'img': ['src'],
          'a' : ['target'] 
        },
       }

在这里我想设置或覆盖 target = "_blank" 。如何在sanitize-html 中实现这一点?

很遗憾,我找不到 sanitize-html 的标签。

【问题讨论】:

  • 您是否尝试将'a' 添加到'*': ['a', 'href', 'align', 'alt', 'center', 'bgcolor', 'style', 'width'] 并尝试使用transformTags

标签: javascript html dom


【解决方案1】:

根据 READ.MD/doc 和您的问题描述,类似:

__html = sanitizeHTML(children, {
    ...,
    transformTags: {
      'a': function(tagName, attribs) {// simpleTransform also possible...
       return {
        tagName: 'a',//tagName
        attribs: {
            target: '_blank',
            href:   '*'
        }
    };
}

...应该这样做。

编辑:

保留当前(允许!)属性的更好解决方案:

....
 transformTags: {
   'a': sanitizeHtml.simpleTransform('a', {target: '_blank'})
 }

【讨论】:

  • 但无法悬停链接
  • 我真的不知道为什么它仍然无法在同一个标​​签中打开。
  • 是的,它有效。唯一的事情是我们需要将'a' : ['target'] 保留在allowedAttributes
  • 谢谢@xerx593
猜你喜欢
  • 2020-05-21
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多