简体   繁体   English

如何在'sanitize-html'中的锚标记中设置或覆盖target =“_ blank”?

[英]How to set or override target= “_blank” in anchor tag in 'sanitize-html' ?

I am using sanitize-html in my project. 我在我的项目中使用sanitize-html Say suppose I get a mail which has anchor tag, something like this: this is to test something <a href="https://www.google.com/">open google</a> 假设我收到一封带有锚标记的邮件,如下所示: this is to test something <a href="https://www.google.com/">open google</a>

This mail appears in my mail box like this : this is to test something open google 这封邮件出现在我的邮箱中,如下所示: this is to test something open google

Which opens google.com in the same tab. 这会在同一个标​​签中打开google.com。 But I need to open in new tab . 我需要在新标签中打开 Here is my code. 这是我的代码。

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

Here I want to set or override target = "_blank" . 在这里,我想设置或覆盖target =“_ blank”。 How to achieve that in sanitize-html ? 如何在sanitize-html中实现这一点?

Unfortunately I could not find a tag for sanitize-html. 很遗憾,我找不到sanitize-html的标签。

According to READ.MD/doc and your problem description, something like: 根据READ.MD/doc和您的问题描述,类似于:

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

...should do it. ......应该这样做。

EDIT: 编辑:

A better solution preserving the current (allowed!) attributes: 保留当前(允许!)属性的更好解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更换<br />标记名称到 sanitize-html JavaScript 中的空格? - How to replace <br /> tag name to white space in sanitize-html JavaScript? sanitize-html npm模块在Heroku部署上不起作用 - sanitize-html npm module not working on Heroku deploy 使用“sanitize-html”npm package 对 HTML 进行消毒的问题 - issue with sanitizing HTML using "sanitize-html" npm package 如何在 DIV 标签中设置目标 =“_blank”? - How to set a target="_blank" in a DIV tag? 如何覆盖 target=&quot;_blank&quot; 行为 - How to override target="_blank" behavior 添加target =“ _ blank”后,div的onclick覆盖了锚标签 - Anchor tag overridden by div's onclick upon adding target=“_blank” Selenium C#-如何从锚标记中删除或替换target = _blank - Selenium C# - How to Remove or Replace target=_blank from an anchor tag SimpleMDE:如何设置 Html 预览以在新选项卡中打开锚标记? - SimpleMDE: How to set Html preview to open anchor tag in a new tab? 在Chrome中使用目标“ _blank”将锚href设置为“ blob:” URL的问题 - Issue with anchor href set to a “blob:” URL using a target of “_blank” in Chrome 如何设置数据目标锚标记的样式 - How to style a data-target anchor tag
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM